I want to append shell script output to a specific line in a file.
Is it possible to do something like that, But to append the output in the third line of the file, Instead of the end of the file?
sh ./myScript.sh >> myFile.txt I want to append shell script output to a specific line in a file.
Is it possible to do something like that, But to append the output in the third line of the file, Instead of the end of the file?
sh ./myScript.sh >> myFile.txt This solution works by saving the first 3 lines to /tmp/first, saving the rest of the file to /tmp/last, saving the output of myScript.sh to /tmp/middle then cating them all back together and overwriting the original /tmp/file:
file=/tmp/file sed -n '1p;2p;3p' "${file}" >/tmp/first sed '1d;2d;3d' "${file}" >/tmp/last ./myScript.sh >/tmp/middle cat /tmp/first /tmp/middle /tmp/last >/tmp/file If you have access to GNU sed then you could do the targeted append to the 3rd line of your input file like this:
sh ./myScript.sh | sed -i -e '3r /dev/stdin' myFile.txt If the output of myScript.sh is one or more lines, and you want it inserted as new lines in between lines 3 and 4 of the original file:
$ sh ./myScript.sh | perl -i -pe 'print <STDIN> if $.==4' myFile.txt In the above, change <STDIN> to <STDIN>,"\n" if the output of myScript.sh doesn't end on a newline.
If the output of myScript.sh is a single line, and you want it appended to the end of the third line, without inserting a new line:
$ sh ./myScript.sh | perl -i -ple 'chomp($_.=<STDIN>) if $.==3' myFile.txt