开发者

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.

开发者_如何学JAVA

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!


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.


  • 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


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;


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}.


Try to create a variable coming from vault/Hashicorp, when using packer template variables, like so:

BUILD_PASSWORD=$(vault read secret/buildAccount| grep ^password | awk '{print $2}')
echo $BUILD_PASSWORD

You can to the same with grep ^user

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜