2

I am trying to add field headers to a file in-place using gawk. The input file is tab delimited so I added that to the command. If I substitute gawk -i inplace with just awk the command runs but the file is not updated. I know awk doesn't have an in-place edit like sed, but can gawk be used or is there a better way?

gawk -i inplace '
BEGIN {FS = OFS = "\t"
}
NR == 1 {
$1= "Chr"
$2= "Start"
$3= "End"
$4= "Gene"
}
1' file

file (input file to update)

chr7    121738788   121738930   AASS
chr7    121738788   121738930   AASS
chr7    121738788   121738930   AASS

desired output

Chr     Start       End         Gene
chr7    121738788   121738930   AASS
chr7    121738788   121738930   AASS
chr7    121738788   121738930   AASS

I was using the SO Q&A awk save modifications in place as a guide but was not able to solve my issue.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
justaguy
  • 2,908
  • 4
  • 17
  • 36

2 Answers2

1
awk 'BEGIN {print  "Chr\tStart\tEnd\tGene"}1' file > newFile && mv newFile file

Output

Chr     Start   End     Gene
chr7    121738788   121738930   AASS
chr7    121738788   121738930   AASS
chr7    121738788   121738930   AASS

As it seems you're mostly interested in adding a header line, just print that before anything happens (via the BEGIN block). The 1 is a "true" statement, so all lines of input are printed (by default). You could replace it with the long hand {print $0} if you want code that non awk-gurus will understand.

Even using a -i inplace option, the program is doing the same as awk 'code' file > newFile && mv newFile file behind the scenes, so there is no "savings" in processing to adding a header to a file. The file has to be rewritten in either case.

IHTH

shellter
  • 36,525
  • 7
  • 83
  • 90
1

It'd be more efficient to just do:

cat - file <<<$'Chr\tStart\tEnd\tGene' > newfile && mv newfile file

with no awk involvement at all.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185