34

I have an external program that produces an output file (largish, 20K lines possible).

I need to insert a new line between the existing line 1 and line 2. I've been looking at awk and sed - I use one liners in each fairly regularly - but I haven't been able to come up with the right switches to do this.

12 Answers 12

23
awk 'NR==1{print; print "new line"} NR!=1'
4
  • 12
    A little shorter: awk 'NR==2 {print "new line"} 1' Jan 23, 2012 at 17:31
  • @glennjackman: your version doesn't work on my system, but the answer does. Specifically, with yours, line 2 is duplicated and the new line is inserted between both (so as line 3). Feb 21, 2014 at 0:36
  • Is there a way to start writing at the 2nd line and overwrite all subsequent lines? Jul 5, 2015 at 2:33
  • @CMCDragonkai I'm not quite sure what you're asking for. Just print the first line of the specified file and a set second line? First line and then the contents of a file? The first line of the first file and then a line from a second file for each remaining line in the first? You may want to ask a new question with a very specific description of what you want, and a relatively short but complete example.
    – Kevin
    Jul 5, 2015 at 2:54
16

For your specific case, this should be simpler:

sed '1 { P ; x }' your-file

Explanation: at line 1, do the following

  1. Print the line
  2. 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.

2
  • 1
    sed -i '1 a\\' file for just a newline.
    – forcefsck
    Jan 23, 2012 at 18:13
  • 1
    @forcefsck Yes, only disadvantage is that it's a GNUism, as my second '1 aapended line' example.
    – angus
    Jan 24, 2012 at 10:36
9

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

3
sed ':a;N;$!ba;s/\n/\n\n\n/' yourBigFile

Explanation.

3

None of the answers above mention how to save the changes to the original file, which is I think what the OP was asking for.

It's certainly what I needed when I cam to the page.

So assuming your file is called output.txt

sed -i '1 a This is the second line' output.txt

My particular use case is to automatically add an xsl stylesheet declaration to a junit xml file.

sed -i '1 a <?xml-stylesheet type="text/xsl" href="junit-html.xsl"?>' junit.xml
2
  • yourownlinux.com/2015/04/… is the relevant part of a well written intro to sed.
    – chim
    Jun 16, 2016 at 10:09
  • 1
    this is what I am looking for thanks man...
    – goodman
    Mar 30, 2020 at 12:04
2

This might work for you:

sed 1G file

If you want to insert something after the newline:

sed '1{G;s/$/something/}' file

Or if you sed handles \n:

sed '1s/$/\nsomething/' file

Of course a is even easier:

sed '1a something' file
3
  • I am sorry, what does it do? Jan 28, 2012 at 8:31
  • It inserts a newline after line 1
    – potong
    Jan 30, 2012 at 14:20
  • 1
    Or rather appends a newline \n to line one!
    – potong
    Jan 30, 2012 at 14:36
1

I usually use ed for this:

(echo 1a; echo 'Line to insert'; echo .; echo w) | ed - filename

Similar to a sed solution, but without the clutter of escaped newlines.

4
  • 2
    You could spare some echo's, especially under bash: ed - filename <<< $'1a\nLine to insert\n.\nw'.
    – manatwork
    Jan 28, 2012 at 16:56
  • 1
    Doesn't work in all shells, for example in dash, which on many systems is /bin/sh.
    – Arcege
    Jan 28, 2012 at 17:26
  • 1
    That is why I wrote “You could spare some echo's”. Sparing all echo's is indeed bash only feature, but reducing the echo count from 4 to 1 works in dash and ksh too: echo '1a\nLine to insert\n.\nw' | ed - filename.
    – manatwork
    Jan 28, 2012 at 17:37
  • 1
    Or just use printf %s\\n, which puts a newline after every arg you give it and doesn't screw up on special characters embedded in the line you want to insert. Also, why use ed when ex is available?
    – Wildcard
    Apr 12, 2016 at 1:54
1

Python Solution

python -c "import sys; lines = sys.stdin.readlines(); lines.insert(1,'New Line\n'); print ''.join(lines).strip()" < input.txt
0

Using sed and (Bash-specific) ANSI escape codes:

# note: \ --> \\
printf '%s\n' 1 2 3 4 5 | sed -e $'1 { s/\\(.*\\)/\\1\\\ninserted line/; }'
0

i would use python for this

import fileinput

for linenum,line in enumerate(fileinput,FileInput("file",inplace=1)):
    if linenum ==1:
          print ""
          print line.rstrip() 
      else: 
          print line.rstrip()`
0

I just like using an explicit counter:

awk '(c==1) {print "new line"} (c!=1) {print $0} {c++}' file
0

Simplest method uses printf and ex:

printf '%s\n' 1a 'my line to insert' . x | ex file

1a means "append after first line"; the . ends the appending; x means save and exit.

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.