How to pass AWK output into variable?

JavaNoob picture JavaNoob · Sep 24, 2010 · Viewed 30.3k times · Source

I have a small bash script that greps/awk paragraph by using a keyword.

But after adding in the extra codes : set var = "(......)" it only prints a blank line and not the paragraph.

So I would like to ask if anyone knows how to properly pass the awk output into a variable for outputting?

My codes:

#!/bin/sh

set var = "(awk 'BEGIN{RS=ORS="\n\n";FS=OFS="\n"}/FileHeader/' /root/Desktop
/logs/Default.log)"
echo $var;

Thanks!

Answer

lesmana picture lesmana · Sep 24, 2010

Use command substitution to capture the output of a process.

#!/bin/sh

VAR="$(awk 'BEGIN{RS=ORS="\n\n";FS=OFS="\n"}/FileHeader/' /root/Desktop/logs/Default.log)"
echo "$VAR"

some general advice with regards to shell scripting:

  • (almost) always quote every variable reference.
  • never put spaces around the equals sign in variable assignment.