-2

Looking to set a date variable withing awk but can't get the quoting or syntax right!

awk -v c=$i -v d="date +\"%D %r %Z\"" '{print d c }'
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Tony
  • 8,681
  • 7
  • 36
  • 55
  • 2
    @Tony Huh? What a rude comment. Please delete it or consider changing to something more constructive. – Maroun Feb 06 '18 at 20:35
  • Try `BEGIN` before the `{print d c }`, or otherwise you have to supply some input lines to get `awk` to execute the `print`. – Kaz Feb 06 '18 at 20:41
  • 3
    Can you include actual and expected output? – that other guy Feb 06 '18 at 20:42
  • 3
    A title that distinguishes this question from [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) and [Assigning system command's output to variable](https://stackoverflow.com/questions/1960895/assigning-system-commands-output-to-variable) would be an improvement. The current title ("*awk variable quotes and escaping*") is so vague that without clicking through, one could expect it to be a duplicate of either or both. – Charles Duffy Feb 06 '18 at 21:02

1 Answers1

5

Consider instead:

awk -v d="$(date +'%D %r %Z')" 'BEGIN{print d}'

The changes here are:

  1. Use $() to execute date and get the output back for the variable d.
  2. Using single quotes for the date format so you don't have double quotes in double quotes
  3. Using BEGIN to execute the print statement in awk. This isn't necessary if you are feeding a file or stdin to awk for it to read records.
JNevill
  • 46,980
  • 4
  • 38
  • 63
  • 1
    Double quotes inside the double quotes would be fine now that you're adding a `$()`-based command substitution -- since that creates a whole new quoting context; `d="$(date +"%D %r %Z")"` would work just as well as the current answer does. As such, while its suggestion (of using single-quotes wherever possible) *is* best practice, I'm not sure that the first line of this answer is on-point. – Charles Duffy Feb 06 '18 at 21:04
  • @CharlesDuffy How right you are. My first instinct was to pull my hair out on behalf of OP and then fix it all up. But in fixing it all up I solved the hair pulling out scenario. I've removed my first sentence! – JNevill Feb 06 '18 at 21:10
  • 1
    There's some chance OP wants to timestamp each line of output as it comes in, but it's not clear from the question – that other guy Feb 06 '18 at 21:13
  • @thatotherguy I have to imagine that's the case here too, which is why I mentioned that the `BEGIN` is only to make this completely superfluous and utterly useless waste of resource sample code to work. – JNevill Feb 06 '18 at 21:51