Sai Karthik

Balancing the braces ...

How to append / prepend text to files in Bash

May 5, 2024 | 1 minute read

There are multiple ways to append/prepend text to files. I am demonstrating the methods which i regularly use.

First, Let’s check the contents of the file fruits.txt

1
2
3
cat fruits.txt
mango
banana

Appending Text:

We could use the symbol >> to append text to a file

1
2
# add the word grapes to fruits.txt
echo grapes >> fruits.txt

Now, Let’s check the contents again

1
2
3
4
cat fruits.txt
mango
banana
grapes

You can observe that the grapes is added to the last line of the file.

Prepending Text:

This will add text to the beginning of the file

1
2
# add the word grapes to beginning fruits.txt
echo -e "grapes\n$(cat fruits.txt)" > fruits.txt

Let’s see the output of the file

1
2
3
4
cat fruits.txt
grapes
mango
banana

You can observe that the grapes is added to the first line of the file.

Comment | Share

Tags: bash