12

I'm working on a bash script that will split the contents of a text document depending on the data in the line.

If the contents of the original file were along the lines of

01 line
01 line
02 line
02 line

How can I insert into line 3 of this file using bash to result in

01 line
01 line
text to insert
02 line
02 line

I'm hoping to do this using a heredoc or something similar in my script

#!/bin/bash

vim -e -s ./file.txt <<- HEREDOC
    :3 | startinsert | "text to insert\n"
    :update
    :quit
HEREDOC

The above doesn't work of course but any recommendations that I could implement into this bash script?

14

You can use Vim in Ex mode:

ex -s -c '3i|hello world' -c x file.txt
  1. 3 select line 3

  2. i insert text and newline

  3. x write if changes have been made (they have) and exit

Or by matching string:

ex -s -c '/hello/i|world' -c x file.txt
8

sed would be a traditional choice (GNU sed probably has an easier form than this).

$ cat input
01 line
01 line
02 line
02 line
$ sed '2a\
text to insert
' < input
01 line
01 line
text to insert
02 line
02 line
$ 

Or, being extremely traditional, ed (bonus! in-place edit without the unportable sed -i form).

$ (echo 2; echo a; echo text to insert; echo .; echo wq) | ed input
32
01 line
47
$ cat input
01 line
01 line
text to insert
02 line
02 line
$ 

(This has nothing to do with bash.)

  • 2
    added bonux replace echo text to insert by cat file-to-insert.txt – Archemar Mar 22 '16 at 15:06
  • 1
    At least with bash, instead of all those echos, you could use printf '%s\n' 2 a 'text to insert' . wq – evilsoup Mar 22 '16 at 22:58
5

How about something like:

head -n 2 ./file.txt > newfile.txt
echo "text to insert" >> newfile.txt
tail -n +3 ./file.txt >> newfile.txt
mv newfile.txt file.txt
  • Strange but interesting idea +1 – Tyþë-Ø Jun 7 at 20:27
2
$ awk 'NR==3{print "text to insert"}1' a.txt
01 line
01 line
text to insert
02 line
02 line

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.