Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add lines at the beginning of either empty or not file?

I want to add lines at beginning of file, it works with:

sed -i '1s/^/#INFO\tFORMAT\tunknown\n/' file
sed -i '1s/^/##phasing=none\n/' file

However it doesn’t work when my file is empty. I found these commands:

echo > file && sed '1s/^/#INFO\tFORMAT\tunknown\n/' -i file

echo > file && sed '1s/^/##phasing=none\n/' -i file

but the last one erase the first one (and also if file isn’t empty)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to know how to add lines at the beginning of file either if the file is empty or not

I tried a loop with if [ -s file ] but without success

Thanks!

>Solution :

You should use i command in sed:

file='inputFile'
# insert a line break if file is empty
[[ ! -s $file ]] && echo > "$file"

sed -i.bak $'1i\
#INFO\tFORMAT\tunknown
' "$file"

Or you can ditch sed and do it in the shell using printf:

{ printf '#INFO\tFORMAT\tunknown\n'; cat file; } > file.new &&
mv file.new file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading