0

Like a reverse of awk 'NR==2 {print ""} 1 which adds a new line under the first and prints whatever there. I can't replace the number after NR== with a fixed value because I want to be able to do this at file including any amount of lines. I mean I suppose I could do something that counts the amount of lines and then make a variable which is the number of the second last line, but I don't want to "reinvent the wheel".

Example input:

1
2
3
4

Example output:

1
2
3
something added here
4
  • 1
    I meant sed '$i\something' (there's a newline after the backslash).. – don_crissti Dec 12 '15 at 1:17
0

You could delay printing by a line, and then use an END block:

awk 'NR > 1 {print line} {line = $0} END {printf "%s\n%s\n", "something added here", line}'

I save the current line in line, and then print in the next iteration. In the END block, therefore, line is the last line, which has not been printed yet.

$ printf "%s\n" {1..4} | awk 'NR > 1{print line} {line = $0} END {printf "%s\n%s\n", "something added here", line}'
1
2
3
something added here
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.