1

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 
1
  • 4
    Does the shell script output one line or more than one line? Do you want to append its output to the end of the third line (no new line is inserted), or do you want to insert its output as new lines between the third and fourth lines of the file? Commented Jun 13, 2018 at 11:09

3 Answers 3

3

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 
2

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 
0

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 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.