Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a blank line before the first line in a text file with awk

Tags:

awk

I have some text files. I would like to add a blank line before the first line in each text file. How can I do this with awk?

like image 651
user1606106 Avatar asked Sep 30 '12 04:09

user1606106


People also ask

How will you insert a line before the first line?

Use sed 's insert ( i ) option which will insert the text in the preceding line. Also note that some non-GNU sed implementations (for example the one on macOS) require an argument for the -i flag (use -i '' to get the same effect as with GNU sed ).

How do I add a new line in awk?

Original answer: Append printf "\n" at the end of each awk action {} . printf "\n" will print a newline.


Video Answer


2 Answers

I would prefer GNU sed for this task:

To add a space to the beginning of the file:

sed '1s/.*/ &/' file.txt

To perform this on multiple text files with the .txt extension, and make the changes directly to the files (i.e. overwrite them), try:

sed -s -i '1s/.*/ &/' *.txt

To add a blank line at the beginning of the file:

sed '1i\\' file.txt

To perform this on multiple text files with the .txt extension, and make the changes directly to the files (i.e. overwrite them), try:

sed -s -i '1i\\' *.txt
like image 123
Steve Avatar answered Sep 22 '22 05:09

Steve


This will give you a blank space at the start of your data file:

 awk 'BEGIN{printf(" ")}1' data.txt

Alternatively, this will give you a blank line at the start of your data file.

 awk 'BEGIN{print""}1' data.txt
like image 41
Levon Avatar answered Sep 21 '22 05:09

Levon