Home > Software engineering >  Insert rows using awk
Insert rows using awk

Time:12-06

How can I insert a row using awk?

My file looks as:

1       43
2       34
3       65
4       75

I would like to insert three rows with "?" So my desire file looks as:

1       ?
2       ?
3       ?
4       43
5       34
6       65
7       75

I am trying with the below script.

awk '{if(NR<=3){print "NR        ?"}} {printf" " NR      $2}' file.txt

CodePudding user response:

Here's one way to do it:

$ awk 'BEGIN{s="       "; for(c=1; c<4; c  ) print c s "?"}
       {print c s $2; c  }' ip.txt 
1       ?
2       ?
3       ?
4       43
5       34
6       65
7       75

CodePudding user response:

$ awk 'BEGIN {printf "1 ?\n2 ?\n3 ?\n"} {printf "%d", $1   3; printf " %s\n", $2}' file.txt
1 ?
2 ?
3 ?
4 43
5 34
6 65
7 75

CodePudding user response:

You could also add the 3 lines before awk, e.g.:

{ seq 3; cat file.txt; } | awk 'NR <= 3 { $2 = "?" } $1 = NR' OFS='\t'

Output:

1       ?
2       ?
3       ?
4       43
5       34
6       65
7       75

CodePudding user response:

I would do it following way using GNU AWK, let file.txt content be

1       43
2       34
3       65
4       75

then

awk 'BEGIN{OFS="       "}NR==1{print 1,"?";print 2,"?";print 3,"?"}{print NR 3,$2}' file.txt

output

1       ?
2       ?
3       ?
4       43
5       34
6       65
7       75

Explanation: I set output field separator (OFS) to 7 spaces. For 1st row I do print three lines which consisting of subsequent number and ? sheared by output field separator. You might elect to do this using for loop, especially if you expect that requirement might change here. For every line I print number of row plus 4 (to keep order) and 2nd column ($2). Thanks to use of OFS, you would need to make only one change if requirement regarding number of spaces will be altered. Note that construct like

{if(condition){dosomething}}

might be written in GNU AWK in more concise manner as

(condition){dosomething}

(tested in gawk 4.2.1)

  • Related