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

Here is one line solution:

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-1\n$(cat input)” > input cat input

To add multiple lines:

echo -e “DATA-Line-1\nDATA-Line-2\n$(cat input)” > input cat input

Use sed command to prepend data to a text file

The syntax is:

sed ‘1s;^;DATA-Line-1\n;’ input > output ## OR ## sed -i ‘1s;^;DATA-Line-1\n;’ 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-1\nForce-2\n;' 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

The sed syntax is:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *