Shell Programming: Adding lines to a file, before and after the file contents

Sunday, July 27, 2008

While appending lines after the contents of the file is a relatively easy task using cat command, I came across several applications where I need to add lines before the contents of the file in bash shell.

One can use cat >> command to append contents to the end of file, but if you need to add/print lines before or after the file's content, the following combination of echo and cat commands may also be useful.

For example, assume that the file newfile.txt has the following content.
bash-3.00$ cat newfile.txt
This is the first line of the file
This is the second line of the file
bash-3.00$
The below commands add/print single/multiple lines before and after the file's contents respectively.

Add lines before the contents of the file:
bash-3.00$ echo -e "This is the start of file\nNow printing the contents of the file" | cat - newfile.txt
This is the start of file
Now printing the contents of the file
This is the first line of the file
This is the second line of the file
bash-3.00$
Add lines after the contents of the file:
bash-3.00$ echo -e "This is the end of the file\nThe file contents are printed" | cat newfile.txt -
This is the first line of the file
This is the second line of the file
This is the end of the file
The file contents are printed
bash-3.00$
One more thing to note in the above command is the usage echo -e to output newline characters, for example there is a variable with /n character, then using echo -e would print a new line instead of /n, to see the difference, look at the commands below.
bash-3.00$ var="This is the first line\nThis is the second line"

bash-3.00$ echo $var
This is the first line\nThis is the second line
bash-3.00$

bash-3.00$ echo -e $var
This is the first line
This is the second line
bash-3.00$

3 comments:

ginko said...

Even though there are various graphical interfaces available for Linux the shell still is a very neat tool. The shell is not just a collection of commands but a really good programming language.You can automate a lot of tasks with it, the shell is very good for system administration tasks.

Anonymous said...

Thanks for the tip.

SUPREME KAISER said...

In the paragraph explaining "echo -e" it should say "\n" instead of "/n".
Must also show a pipe out to a file since your talking about adding to a file instead of stdout.

But all in all, this is a good post.


Copyright © 2016 Prasanna Seshadri, www.prasannatech.net, All Rights Reserved.
No part of the content or this site may be reproduced without prior written permission of the author.