Single quote in awk
For the first one
$ awk '{print "me "$0 '"notme"} <<<"printme"
What's happening here is:
- The part in single quotes is passed to
awk
verbatim - The next part
"notme"}
is parsed by the shell and then passed toawk
as the resulting stringnotme}
awk
gets to see this:{print "me "$0 notme}
Since the
awk
variablenotme
has no value, that's what you get
For the second one
$ awk '{print "me "$0 '"\"$(date)"\"} <<<"printme-at " me printme-at Wed Apr 11 16:41:34 DST 2018
I'd be more inclined to write it like this, using an awk
variable to carry the value of $(date)
:
awk -v date="$(date)" '{print "me "$0 date}' <<<"printme-at "
me printme-at Wed Apr 11 13:43:31 BST 2018
You've asked why there is no syntax error in your version of this one. Let's take it apart:
# typed at the shell
awk '{print "me "$0 '"\"$(date)"\"} <<<"printme-at "
# prepared for awk
awk '{print "me "$0 "Wed Apr 11 16:41:34 DST 2018"}' <<<"printme-at "
# seen by awk
{print "me "$0 "Wed Apr 11 16:41:34 DST 2018"}
The double-quoted string "\"$(date)\""
is parsed by the shell before awk
gets anywhere near it, and is evaluated (by the shell) as something like the literal string "Wed Apr 11 13:43:31 BST 2018"
(including the double-quote marks). I don't see why there needs to be a syntax error as what you have written is valid - although somewhat tortuous to read.
The single quote ends the string that delimits the awk
program in the shell. awk
itself will never see it. You then concatenate that initial part of the program with more strings provided by command substitutions and static strings in the shell. This all happens before awk
has been invoked.
Of course you could use command substitutions to modify a string that later is read by awk
as its code, but it does not really make for easy to read code, and may be rather fragile with regards to the shell's quoting rules, word splitting etc.
It would be better to just set an awk
variable in the usual way:
awk -v thedate="$(date)" '{ print $0, thedate }' <<<"something"