I would like to add a header line containing whitespaces to multiple files.
Here is what I have so far:
#!/bin/bash
# script name is "add_header.sh"
# ARG1 = HEADER STRING
# ARG2,3,... = ARRAY OF FILES TO ADD HEADER TO, RELATIVE DIRECTORY
HEADER=$1
shift
for FILE in $@; do
awk -v HEADER=$HEADER FILE=$FILE 'BEGIN{print HEADER} {print}' FILE > FILE.new
done
Unfortunately, when I run it on my use case, it fails because of the white spaces:
touch file1 file2 file3
./add_header.sh "some header with spaces" file1 file2 file3
which gives following error:
awk: fatal: cannot open file `with' for reading (No such file or directory)
awk: fatal: cannot open file `with' for reading (No such file or directory)
awk: fatal: cannot open file `with' for reading (No such file or directory)
Is there a way to escape white spaces inside a bash variable? I have tried using \ before each space, but the error now changes to:
./add_header.sh "some\ header\ with\ spaces" file1 file2 file3
awk: fatal: cannot open file `with\' for reading (No such file or directory)
awk: fatal: cannot open file `with\' for reading (No such file or directory)
awk: fatal: cannot open file `with\' for reading (No such file or directory)
which means the whitespaces are not being escaped.
FILEdoes not exist. You need to use"$FILE"at the end of the command e.gawk -v HEADER="$HEADER" -v FILE="$FILE" 'BEGIN{print HEADER} {print > FILE".new"}' "$FILE"header="$1",awk HEADER="$header" .... Avoid upper case variable names. Always paste your script intohttps://shellcheck.net, a syntax checker, or installshellchecklocally. Make usingshellcheckpart of your development process.-vflag for the FILE argument. However,{print > FILE".new"}does not work.