user2182606
user2182606

Reputation: 61

Add new lines up to specific row

Hoping somebody can help me out.

I have large number of files with different number of lines. I would like to add new lines in to the files up to specific rows, say 6.

Infile.txt

text1 
text2
text3 

The out file I would like to have is

Outfile.txt

text1 
text2
text3 
\n 
\n 
\n

Upvotes: 1

Views: 184

Answers (3)

Ed Morton
Ed Morton

Reputation: 203149

IMHO the clearest and most obvious way to handle this is to simply loop from the last line number plus 1 to the target number of lines:

$ seq 3 | awk -v n=6 '{print} END{for (i=NR+1; i<=n; i++) print ""}'
1
2
3



$

You can also count down if you want to save a variable:

$ seq 3 | awk -v n=6 '{print} END{while (n-- > NR) print ""}'
1
2
3



$

but IMHO that's sacrificing clarity in favor of brevity and not worthwhile.

Upvotes: 1

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short awk solution:

awk -v r=6 'END{ while((r--)-NR>0) print "" }1' file
  • -v r=6 - variable r indicating total/maximal number of rows

Upvotes: 3

jas
jas

Reputation: 10865

In awk's END block, the built-in variable NR will contain the row number of the last line of the file. From there it's easy to print the needed number of additional empty rows.

$ awk -v lines=6 '1; END {for (i=NR; i<lines; ++i) print ""}' file 
text1
text2
text3



$ awk -v lines=6 '1; END {for (i=NR; i<lines; ++i) print ""}' file | wc -l
6

Upvotes: 1

Related Questions