banner

For a list of BASHing data 2 blog posts see the index page.    RSS


Four ways to prepend a line of text

In BASH, it's easy to add a line or lines to the bottom of a text file, because BASH has an "append" operator, ">>":

append

It's not so easy to add a line or lines to the top of a text file, because in BASH there isn't a "prepend" operator. "Not so easy" doesn't mean "horribly difficult", though, and there are some simple ways to do this job. In each case below I add the header line "CustomerID,Date,ReceiptNo" to the top of the following file, which I'll call "account". To save space I'll store the header line in the variable "header":

AK0012Q,2025-06-13,47195
AK0003N,2025-06-13,47196
AK0001B,2025-06-14,47197

NOTE that in all four cases below the original "account" file is overwritten and lost. To be safer in real-world operations I would send the prepend result to a new file, like "account-with-header". I do this with "append" operations, too!


Insert with sed

sed -i "1i $header" account

sed

The -i option tells sed to modify the original file (edit in place). At line 1, sed inserts (i) the string in "header", which is expanded by the shell because the sed command is enclosed in double rather than single quotes.


cat to a temp file, mv the temp file

echo "$header" | cat - account > junk && mv junk account

cat-mv

cat concatenates stdin and "account", and stdin is the string in "header". The concatenation is saved in the file "junk", which is then renamed "account" by mv, overwriting the original "account". This is the prepending method I've seen most often in BASH tutorials on the Web.


printf and a cat

printf "$header\n$(cat account)" > account

echo-cat

The BASH built-in printf here prints the string in "header", a newline, the result of catting "account", and another newline. The result is saved as "account", overwriting the original file.


two cats and an Enter

cat <<<"$header      #Press "Enter" at this point
($cat account)" > account

2-cat

This ingenious solution is from Melvin Roest in a 2020 post to Superuser on Stack Exchange. cat can print a herestring, and with this method the herestring consists of the string in "header", a literal newline entered by the user, and the result of catting "account". Putting a newline character in the herestring doesn't produce a newline in the output.


Next post:
2025-10-17   Mojibake detective: the case of the Greek claw


Last update: 2025-10-10
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License