Insert text at specific line number

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


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


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