20

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?

5 Answers5

22

You can use the POSIX tool ex by line number:

ex a.txt <<eof
3 insert
Sunday
.
xit
eof

Or string match:

ex a.txt <<eof
/Monday/ insert
Sunday
.
xit
eof

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ex.html

Zombo
  • 1
  • 5
  • 44
  • 63
15

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.)

thrig
  • 34,938
13
$ awk 'NR==3{print "text to insert"}1' a.txt
01 line
01 line
text to insert
02 line
02 line
Kamaraj
  • 4,365
  • can be used as awk -i inplace '...' for a one-line equivalent of the sed -i solution. See https://stackoverflow.com/questions/16529716/ – eddygeek Mar 04 '21 at 18:50
9

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
1

Try the following:

Your original file

$ cat <<'EOF' > file.txt
01 line
01 line
02 line
02 line
EOF

insert into line 3 using a heredoc.

$ cat <<'EOF' | sed -i "3r /dev/stdin" file.txt
text to insert
EOF

you get this result

$ cat file.txt
01 line
01 line
text to insert
02 line
02 line

UPDATED: Following the comment of @Kusalananda

wolfrevo
  • 111