curiousaboutpi curiousaboutpi - 4 months ago 15
Bash Question

Awk dealing with variables containing whitespace

I want to pass a string with whitespaces as a variable to awk from a Bash script, but independent of how I escape it, awk will complain. Please consider the following example:

list1:

one
two
three
four


The output:

[user@actual ~]$ ./dator.sh list1
1470054866 two (...)


A working script:

CMD='awk'
DATE=$(date +%s)
VARIABLES="-v time=$DATE"
SCRIPT='NR>=2 {printf "%s %s\n", time, $1;}'

$CMD $VARIABLES "$SCRIPT" $1


And only changing the date-formatting will break it:

CMD='awk'
DATE=$(date -u)
VARIABLES="-v time=$DATE"
SCRIPT='NR>=2 {printf "%s %s\n", time, $1;}'

$CMD $VARIABLES "$SCRIPT" $1


How should I escape it?


  • Every kind of quoting I'm aware of doesn't work.

  • Translating and inserting escaping "\" before whitespace doesn't make a difference.

  • Printing the variable via a function as suggested in another solution didn't work.


Answer

Arrays were designed for storing arbitrary arguments.

current_date=$(date +%u)
variables=( -v "time=$current_date")
script='NR >= 2 {printf "%s %s\n", time, $1;}'
awk "${variables[@]}" "$script" "$1"
Comments