3

I want to alter a text file. Let's say I have some text on line 22, and I want to make line 22 blank and move down the text on line 22 down to line 23. To illustrate, I want to turn this (printf 'Some %d text\n' {1..23}):

Some 1 text
Some 2 text
Some 3 text
Some 4 text
Some 5 text
Some 6 text
Some 7 text
Some 8 text
Some 9 text
Some 10 text
Some 11 text
Some 12 text
Some 13 text
Some 14 text
Some 15 text
Some 16 text
Some 17 text
Some 18 text
Some 19 text
Some 20 text
Some 21 text
Some 22 text
Some 23 text

into this:

Some 1 text
Some 2 text
Some 3 text
Some 4 text
Some 5 text
Some 6 text
Some 7 text
Some 8 text
Some 9 text
Some 10 text
Some 11 text
Some 12 text
Some 13 text
Some 14 text
Some 15 text
Some 16 text
Some 17 text
Some 18 text
Some 19 text
Some 20 text
Some 21 text
Some 22 text

Some 23 text

How would I do this?

  • I updated your question with sample text, without line numbers. If the change is unacceptable, please feel free to roll it back (by clicking on the "edited..." link and selecting a version to roll back to). – Jeff Schaller Nov 21 at 20:46
5
sed -i '21 a\
' yourfile

21 is previous line number full example on line 1 to append (a) blank line after line 1 :

francois@zaphod:~$ cat toto
Some text
Some more text
Some other text
francois@zaphod:~$ sed -i '1 a\
' toto
francois@zaphod:~$ cat toto
Some text

Some more text
Some other text
francois@zaphod:~$

then file is 4 lines long (including the blank one)

  • Thank you! :) This worked – m004yu Nov 21 at 20:04
  • 2
    21G might be more idiomatic - it appends the (initially empty) contents of the hold space – steeldriver Nov 21 at 20:28
  • 1
    Interestingly, a with blank (or whitespace-only) text does not work on the default BSD-derived sed on MacOS. G works fine. – glenn jackman Nov 21 at 20:32
3

With the standard editor ed, just print the corresponding commands to its input:

printf '%s\n' 22a '' . w q | ed -s file
  1. Append after line 22
  2. (blank line)
  3. . -- end the appended input
  4. write the file to disk
  5. quit ed

Alternatively, insert before line 23 with 23i instead of 22a.

  • I'm guessing this will probably be faster than sed since you don't need to read every line of the file and write every line to a temp file. – glenn jackman Nov 21 at 20:37
1

You can use the following with sed:

$ sed -e '22{x;G;}' file

This will put an empty line (a newline) before the 22nd line. The prior contents of the 22nd line will be pushed down. Note though that the contents of the hold space will be modified by this operation. To preserve , use the below variation:

$ sed -e '22{x;p;x;}' file 

Or with the awk / perl utilities:

$ awk 'NR==22{$0 = RS $0}1' file

$ perl -pe '22..22&&s/^/\n/' file

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.