1

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
  • You need to add 6 empty lines to the files irrespective of the line count and content? OR do you have any logic in doing so? – Srini V Sep 06 '17 at 09:21

3 Answers3

3

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Probably not a problem if you're sure about the data, but be careful of a data file with already more than the desired number of lines --- the while loop will be infinite. (Maybe better to compare `(r--)-NR > 0`) – jas Sep 06 '17 at 12:43
1

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
jas
  • 10,715
  • 2
  • 30
  • 41
1

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.

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