justaguy
justaguy

Reputation: 3022

awk to print text if pattern is meet with nothing under

The below awk is meant to be used for the two possible outcomes of file which is tab delimeted. Option 1 is that file will only contain a header row with nothing under it. Option 2 is file will contain the same header row but with rows under it. The awk reads file and if it is option 1 or header only then 1 0 0 0 0 is printed (with tab seperated). If file is option 2 or a header with rows under it nothing is done. There may be more then one file in the directory but always the same format.

file (option1)

R_Index Chr Start   End Gene

file (option2)

R_Index Chr Start   End Gene
1   1   100 300 xxx
2   2   200 250 yyy

desired output if option 1

R_Index Chr Start   End Gene
1   0   0   0   0

awk

awk -F'\t' '{if ($0 ~ /R_Index\tChr\tStart\tEnd\tGene/) {print "1\t0\t0\t0\t0} else {next}}1' file > tmp && mv tmp file

awk -F'\t' '/R_Index\tChr\tStart\tEnd\tGene/{print "1\t0\t0\t0\t0"; next}1' file

Upvotes: 1

Views: 28

Answers (1)

karakfa
karakfa

Reputation: 67467

this should do:

$ awk -v OFS='\t' 'NR==1 && $0!="R_Index\tChr\tStart\tEnd\tGene"{NR=0; exit 1}1; 
                   END {if(NR==1){print 1,0,0,0,0; exit 0} exit 1}' file > tmp && mv tmp file

exit status will be only successful if the second line needs to be added, which then triggers updating the file via tmp file.

Upvotes: 2

Related Questions