serious
serious

Reputation: 147

Using awk to add a column between $4 and $5

I am interested in being able to add an empty column with no values, that is an empty space followed by a tab into my csv file. I have working code with which I can add a column but I don't understand how to fill it with spaces followed by tab since I am attempting to insert it between two already existing columns $4 and $5 that span over 100k rows.

My code

cat file | NR==1 {print $0,"Ref"; next}

Sample Input File

Position        Food    Age     Occup   Loc     Avg
very stable     eggs    27      busy    out     100%

Expected Output File

Position        Food    Age     Occup   Ref     Loc     Avg
very stable     eggs    27      busy            out     100%

Simply, I am trying to create a column that is still tab-delimited over a span of ~100k rows. Thanks! I am aware that sed might work too.

Upvotes: 2

Views: 416

Answers (2)

Joaquin
Joaquin

Reputation: 2101

You could try:

awk 'NR==1 {print $1,$2,$3,$4,"Ref",$5,$6; next} 
{print $1,$2,$3,$4,"*",$5,$6}' file | column -t | tr "*" " " 

NOTE

I'm assuming that * doesn't appear in file.

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204731

awk 'BEGIN{FS=OFS="\t"} {$5=(NR>1 ? "" : "Ref") OFS $5} 1'

or if you REALLY want a blank char in the "Ref" column of the non-header lines for some reason:

awk 'BEGIN{FS=OFS="\t"} {$5=(NR>1 ? " " : "Ref") OFS $5} 1'

For example:

$ cat file
Position        Food    Age     Occup   Loc     Avg
very stable     eggs    27      busy    out     100%

$ awk 'BEGIN{FS=OFS="\t"} {$5=(NR>1 ? "" : "Ref") OFS $5} 1' file
Position        Food    Age     Occup   Ref     Loc     Avg
very stable     eggs    27      busy            out     100%

Upvotes: 2

Related Questions