0

I have a csv file looks like this:

site1.com,aaa,bbb,ccc
site2.com,qqq
site3.com,rrr,uuu,ppp
site4.com,ddd,sss
site5.com,www,rrr,yyy,uuu
site6.com,,,,ttt,,,,
site7.com,,,uuuu,,,,ppp,
site8.com,,,,ggg,zzz

I want to replace rows (lines) where the nth to mth (2th to 4th) columns are empty. and I want to manipulate said rows by running a command on them. For example, with awk:

awk -F, '$n-$m=="" {printf "%s,",$1 ; system(cmd1) ;}else {print $0}' test.csv
awk -F, '$2-$4=="" {printf "%s,",$1 ; system(cmd1) ;}else {print $0}' test.csv

I then want to export as follows (output1 is output from cmd1 command):

site1.com,aaa,bbb,ccc
site2.com,qqq
site3.com,rrr,uuu,ppp
site4.com,ddd,sss
site5.com,www,rrr,yyy,uuu
site6.com,output1
site7.com,,,uuuu,,,,ppp,
site8.com,output1
  • Please edit and clarify.i) Should rows with <N fields be left alone? ii) Why is site7.com left unchanged in your example? Fields 2-4 are blank there. Should there be at least N+1 fields? – terdon Jan 3 '17 at 10:45
  • sorry you are right – alrz Jan 3 '17 at 11:03
  • OK, and what is system("$1,cmd1 $1") supposed to be? That syntax doesn't make sense. The system() call returns the exit status of the command. Is that what you want? What is the $1,cmd1 $1 supposed to be? – terdon Jan 3 '17 at 11:11
  • $1 is first column. ok i modify. actually cmd1 is a sample shell command or calling function. for example <echo test> – alrz Jan 3 '17 at 11:39
  • Yes, but the system() function of awk returns the exit status and not the command's output. Is that what you want? Or do you want the output of the command? Does it need to be a system call? Can't you just do it in awk directly? – terdon Jan 3 '17 at 12:09
0

Since you only want 3 columns, you can do this with:

awk -F, '{
            if($2=="" && $3==$2 && $3==$4){
                printf "%s,",$1; 
                system("CMD")
            }
            else{print}
          }' test.csv 
  • thanks for answer. but this answer for 2th and 3th and 4th columns. If I want to do for 2th to end columns. how to do ? – alrz Jan 3 '17 at 13:34
  • @alrz did you try it? – terdon Jan 3 '17 at 13:37
  • yes. Works properly. thanks. If possible I want to do for 2th to end columns. for csv file with a lot columns – alrz Jan 3 '17 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.