How to save command output to specific line of text file
I would like to know how to save command output to a specific line of a text file.
I searched on the internet for about an hour about this problem, but I didn't find any proper answer.
For example:
I want to save the output of some ls
command to 7th line of example.txt
.
(insert new line)
How would I do it?
Thanks in advance.
You could use sed's r
command to read and insert the command output after a given address. In particular, GNU sed provides the special filename /dev/stdin
to read data from standard input.
So for example, given
$ cat example.txt
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
then
$ ls -l example.txt | sed -i '7r/dev/stdin' example.txt
results in
$ cat example.txt
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
-rw-r--r-- 1 steeldriver steeldriver 71 Jun 28 15:52 example.txt
Line 8
Line 9
Line 10
If you want the command output inserted before the 7th line, then read and insert it after the 6th.