How can I write to the second line of a file from the command line?
awk 'NR==1{print; print "new line"} NR!=1'
For your specific case, this should be simpler:
sed '1 { P ; x }' your-file
Explanation: at line 1, do the following
- Print the line
- Exchange the pattern space with the holding space (basically empties the buffer)
Then, the line (empty now) is printed again as part of the cycle.
If you want to add a new line instead of a new line character (what I understood initially) then just use sed
's command a\
(append):
sed '1 a\
appended line' your-file
or even
sed '1 aappended line' your-file
It appends "appended line
" after line 1.
I guess the sed
approach would be:
sed '2 i whatever_line_of_text_you_wanted_to_INSERT' filename.txt
This will get the text into the second line of the file and then the the actual second line with in the file will become the third.
Note that, using append mode, if it had to be, it had to use the first line, since the append will happen after the line number noted.
sed '1 a whatever_line_of_text_you_wanted_to_INSERT' filename.txt