Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass AWK output into variable?

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!

like image 844
JavaNoob Avatar asked Sep 24 '10 04:09

JavaNoob


4 Answers

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.
like image 161
Lesmana Avatar answered Oct 21 '22 02:10

Lesmana


  • You need to use "command substitution". Place the command inside either backticks, `COMMAND` or, in a pair of parentheses preceded by a dollar sign, $(COMMAND).
  • To set a variable you don't use set and you can't have spaces before and after the =.

Try this:

var=$(awk 'BEGIN{RS=ORS="\n\n";FS=OFS="\n"}/FileHeader/' /root/Desktop/logs/Default.log)
echo $var
like image 26
dogbane Avatar answered Oct 21 '22 02:10

dogbane


You gave me the idea of this for killing a process :). Just chromium to whatever process you wanna kill.

Try this:

VAR=$(ps -ef | grep -i chromium | awk '{print $2}'); kill -9 $VAR 2>/dev/null; unset VAR;
like image 43
cokedude Avatar answered Oct 21 '22 01:10

cokedude


anytime you see grep piped to awk, you can drop the grep. for the above,

awk '/^password/ {print $2}'

awk can easily replace any text command like cut, tail, wc, tr etc. and especally multiple greps piped next to each other. i.e

grep some_co.mand | a | grep b ... to | awk '/a|b|and so on/ {some action}.
like image 26
jim Avatar answered Oct 21 '22 03:10

jim