BASH: Prepend A Text / Lines To a File

I am a new Unix system user with a bash as a default shell. I can append text to a file using >> operator but how do I prepend a text to a file? I want the opposite operation of >>. How can I prepend some data to a text file?

As far as I know there is no prepend operator on a bash or any other shell, however there are many ways to do the same. You can use ed, sed, perl, awk and so on.

Prepend a text using a temporary file

Here is simple solution using a temporary file to prepend text:

echo 'line 1' > /tmp/newfile
echo 'line 2' >> /tmp/newfile
cat yourfile >> /tmp/newfile
cp /tmp/newfile yourfile

echo ‘line 1’ > /tmp/newfile
echo ‘line 2’ >> /tmp/newfile
cat yourfile >> /tmp/newfile
cp /tmp/newfile yourfile

Here is one line solution:

echo "text"|cat - yourfile > /tmp/out && mv /tmp/out yourfile

echo "text"|cat – yourfile > /tmp/out && mv /tmp/out yourfile

Using bash only solution

No need to create a temp file:

echo -e "DATA-Line-1n$(cat input)" > input
cat input

echo -e "DATA-Line-1n$(cat input)" > input
cat input

To add multiple lines:

echo -e "DATA-Line-1nDATA-Line-2n$(cat input)" > input
cat input

echo -e "DATA-Line-1nDATA-Line-2n$(cat input)" > input
cat input

Use sed command to prepend data to a text file

The syntax is:

sed  '1s;^;DATA-Line-1n;' input > output
## OR ##
sed -i '1s;^;DATA-Line-1n;' input
## verify it ##
cat input

sed ‘1s;^;DATA-Line-1n;’ input > output
## OR ##
sed -i ‘1s;^;DATA-Line-1n;’ input
## verify it ##
cat input

Here is a sample input file:

$ cat input.txt
This is a test file.
I love Unix.

Next prepend two lines (make sure you add n):

$ sed -i '1s;^;Force-1nForce-2n;' input.txt
$ cat input.txt
Force-1
Force-2
This is a test file.
I love Unix.

How do I prepend a string to the beginning of each line in a file?

The awk syntax is:

awk '{print "Line-1" $0}' file

awk ‘{print "Line-1" $0}’ file

The sed syntax is:

sed -i -e 's/^/Line-1/' file

sed -i -e ‘s/^/Line-1/’ file

Examples

Here is our sample file:

$ cat data.txt
Maybe I'm crazy
Maybe you're crazy
Maybe we're crazy
Probably

Use the sed or awk as follows:

$ sed -i -e 's/^/DATA-Here/' data.txt
$ cat data.txt
DATA-HereMaybe I'm crazy
DATA-HereMaybe you're crazy
DATA-HereMaybe we're crazy
DATA-HereProbably

See sed,awk, and bash command man pages for more info.

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.