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

Time:11-27

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)

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!

CodePudding user response:

You can use the insert command (i).

if [ -s file ]; then
    sed -i '1i\
#INFO\tFORMAT\tunknown\
##phasing=none' file

else
    printf '#INFO\tFORMAT\tunknown\n##phasing=none' > file
fi

Note that \t for tab is not POSIX, and does not work on all sed implementations (eg BSD/Apple, -i works differently there too). You can use a raw tab instead, or a variable: tab=$(printf '\t').

CodePudding user response:

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

CodePudding user response:

Explicitely creating a new file, then moving it:

#!/bin/bash
echo -e '#INFO\tFORMAT\tunknown' | cat - file > file.new
mv file.new file

or slurping the whole content of the file into memory:

printf '#INFO\tFORMAT\tunknown\n%s' "$(cat file)" > file

CodePudding user response:

With plain bash and shell utilities:

#!/bin/bash

header=(
        $'#INFO\tFORMAT\tunknown'
        $'##phasing=none'
)

mv file file.bak &&
{ printf '%s\n' "${header[@]}"; cat file.bak; } > file &&
rm file.bak

CodePudding user response:

It is trivial with ed if available/acceptable.

printf '%s\n' '0a' $'#INFO\tFORMAT\tunknown' $'##phasing=none' . ,p w | ed -s file

  • It even creates the file if it does not exists.
  • Related