35

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.

Tim Brigham
  • 1,017

12 Answers12

23
awk 'NR==1{print; print "new line"} NR!=1'
Kevin
  • 40,767
  • 12
    A little shorter: awk 'NR==2 {print "new line"} 1' – glenn jackman Jan 23 '12 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). – Nikana Reklawyks Feb 21 '14 at 00:36
  • Is there a way to start writing at the 2nd line and overwrite all subsequent lines? – CMCDragonkai Jul 05 '15 at 02: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 05 '15 at 02: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.

angus
  • 12,321
  • 3
  • 45
  • 40
13

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

4

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
chim
  • 141
  • http://www.yourownlinux.com/2015/04/sed-command-in-linux-append-and-insert-lines-to-file.html is the relevant part of a well written intro to sed. – chim Jun 16 '16 at 10:09
  • 1
    this is what I am looking for thanks man... – goodman Mar 30 '20 at 12:04
3
sed ':a;N;$!ba;s/\n/\n\n\n/' yourBigFile

Explanation.

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
potong
  • 71
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.

Arcege
  • 22,536
  • 2
    You could spare some echo's, especially under bash: ed - filename <<< $'1a\nLine to insert\n.\nw'. – manatwork Jan 28 '12 at 16:56
  • 1
    Doesn't work in all shells, for example in dash, which on many systems is /bin/sh. – Arcege Jan 28 '12 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 '12 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 '16 at 01:54
1

Python Solution

python -c "import sys; lines = sys.stdin.readlines(); lines.insert(1,'New Line\n'); print ''.join(lines).strip()" < input.txt
Rahul Patil
  • 24,711
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.

Wildcard
  • 36,499
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

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

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

I just like using an explicit counter:

awk '(c==1) {print "new line"} (c!=1) {print $0} {c++}' file
Mat
  • 52,586