Linux – Output of a command to the first line of a file

commandfileslinux

I am trying to insert output of a command into the first line of a file.

For example, I have a file named "list.txt" and want to insert a text containing all the file names in that folder. A way to direct the output of ls command to the first line of list.txt.

Best Answer

Most people know of sed as a tool for search and regex-based search and replece, but it is a full editor capable of making edits.

So You could issue a command like this. Which would insert (1 i) the first line of the ls command $(ls| head -1) into the list.txt file inplace (-i).

sed -i "1 i$(ls| head -1)" list.txt