Score:0

How to save command output to specific line of text file

dk flag

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.

HuHa avatar
es flag
This might be what you need: https://unix.stackexchange.com/questions/70878/replacing-string-based-on-line-number
hr flag
Do you want to overwrite the existing 7th line? or insert the new line before or after it?
カラス avatar
dk flag
@steeldriver insert new one
Score:2
hr flag

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.

カラス avatar
dk flag
It works! Thank you so much.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.