To prepend text or lines to a file in BASH, you can use the echo
command followed by the text you want to add, and then use the cat
command to concatenate the text to the beginning of the file. For example, if you want to prepend the line "This is a new line" to the file "myfile.txt", you can use the following command:
echo "This is a new line" | cat - myfile.txt > temp.txt && mv temp.txt myfile.txt
This will first create a temporary file called "temp.txt" that contains the original contents of "myfile.txt" with the new line added at the beginning. It will then rename the temporary file to replace the original "myfile.txt" file.
Alternatively, you can use the sed
command to insert the new text at the beginning of the file. For example, the following command will insert the text "This is a new line" at the beginning of "myfile.txt":
sed -i '1i\ This is a new line' myfile.txt
Note that the sed
command uses a slightly different syntax for inserting text at a specific line, so be sure to read the documentation for the exact syntax if you choose to use this method.