1

Suppose I have a file abc.csv with below data:

abc
def
geh
ijk
lmn
opq
rst

Now, I want to insert blank lines after line2 and line 6.

Please suggest which command shall I use.

  • What have you tried? I only see one line int hat file - is that all one line, or is it multiple lines and you simply did not format the question correctly? – John Aug 12 '15 at 15:05
  • Does line numbers (where blank ones needs to be inserted) always stay the same? For every file? You must be more clear on that point. What you are asking is possible with awk, sed, perl, bash, etc... – Neven Aug 12 '15 at 15:21
7
$ seq 10 | sed '2G;6G'
1
2

3
4
5
6

7
8
9
10

The G sed command appends a newline followed by the content of the hold space (here empty as we don't put anything in it) to the pattern space. So it's a quick way to add an empty line below that matched line.

Other alternatives are the a and s command:

sed '2a\

6a\
'

Or:

sed '2s/$/\
/
6s/$/\
/'

Some sed implementation also support:

sed '2s/$/\n/;6s/$/\n/'
  • What is the Posix way to do it? Related, why does a simple insert not work? I.e., sed -e '3i ' somefile > somefile.new. – user56041 Jan 15 '18 at 0:56
1
sed -e '2a\ ' -e '6a\ ' input > output && mv output input

Some sed(1) flavours have an -i option to operate on a file "in-place" (but that is not portable), or try sponge from moreutils, but both of those methods are merely hiding the write-to-new-file-and-rename(2)-system-call that the mv does (if the output file is on the same filesystem).

0

This should work:

awk 'NR==3||NR==7 {print " "} {print $0}' abc.csv > temporary.csv && mv temporary.csv abc.csv
  • I want to save the changes in the file. How will that be done? – Nikhil Sinha Aug 12 '15 at 16:34
  • @NikhilSinha I modified the answer and now the changes go to the original file. – jcbermu Aug 13 '15 at 8:29
0

You can use Vim in Ex mode:

ex -sc '6pu_|2pu_|x' abc.csv
  1. pu_ append blank line

  2. x save and close

  • Portably, you would need to avoid the black hole register as it's Vim specific. Instead use the append command: printf %s\\n 6a '' . 2a '' . x | ex abc.csv – Wildcard Apr 12 '16 at 4:10

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.