Hi Guys,
I am new to shell script.I need your help to write a shell script.
I have a csv file which has 13 columns separated by ,
I have written below script to fetch required 5 columns.
awk -F, '(NR==1){h3=$3;h4=$4;h8=$8;h9=$9;h13=$13;next}(NF>1) \
{print h3":"$3"\n"h4":"$4"\n"h8":"$8"\n"h9":"$9"\n"h13":"$13}' $IFILE > $OFILE
Now i want to include condition in above script to check if column 13 is null/empty and if yes print ouptput "error in file".
awk -F, '! $13 { print "Error in file">"/dev/null"; exit }
{print h3":"$3"\n"h4":"$4"\n"h8":"$8"\n"h9":"$9"\n"h13":"$13}' $IFILE > $OFILE
Thanks for the reply.
I am tried by using the below if loop after my print stattement but not working..any idea why.
if [ $h13 == "" ]; then
echo "error in file format column " > $OFILE
also tried
if [ $h13 = "" ]; then
echo "error in file format column " > $OFILE
Because awk is awk, shell is shell, and they don't use each others' variables.
What are you trying to do?
Try this:
if ! awk -F, '! $13 { print "Error in file">"/dev/null"; exit 1 }
{print h3":"$3"\n"h4":"$4"\n"h8":"$8"\n"h9":"$9"\n"h13":"$13}' $IFILE > $OFILE
then
echo "error"
fi
Should be $13==""
not ! $13
; the latter treats a 0
like a ""
.
If you want to include the error in the output file, you can do that in awk
awk -F, '
($13=="") {print "Error in file"; exit 1}
(NR==1) {h3=$3;h4=$4;h8=$8;h9=$9;h13=$13; next}
{print h3":"$3"\n"h4":"$4"\n"h8":"$8"\n"h9":"$9"\n"h13":"$13}
' $IFILE > $OFILE
2 Likes