Linux 如何将 AWK 输出传递给变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3784285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass AWK output into variable?
提问by JavaNoob
I have a small bash script that greps/awk paragraph by using a keyword.
我有一个小的 bash 脚本,它使用关键字来 grep/awk 段落。
But after adding in the extra codes : set var = "(......)"
it only prints a blank line and not the paragraph.
但是在添加了额外的代码之后:set var = "(......)"
它只打印一个空行而不是段落。
So I would like to ask if anyone knows how to properly pass the awk output into a variable for outputting?
所以我想问一下是否有人知道如何将awk输出正确传递到变量中进行输出?
My codes:
我的代码:
#!/bin/sh
set var = "(awk 'BEGIN{RS=ORS="\n\n";FS=OFS="\n"}/FileHeader/' /root/Desktop
/logs/Default.log)"
echo $var;
Thanks!
谢谢!
采纳答案by lesmana
Use command substitutionto 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:
关于 shell 脚本的一些一般建议:
- (almost) always quote every variable reference.
- never put spaces around the equals sign in variable assignment.
- (几乎)总是引用每个变量引用。
- 永远不要在变量赋值中的等号周围放置空格。
回答by dogbane
- 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=
.
- 您需要使用“命令替换”。将命令放在反引号内,
`COMMAND`
或者放在一对以美元符号开头的括号中$(COMMAND)
。 - 要设置一个您不使用的变量
set
,并且=
.前后不能有空格。
Try this:
尝试这个:
var=$(awk 'BEGIN{RS=ORS="\n\n";FS=OFS="\n"}/FileHeader/' /root/Desktop/logs/Default.log)
echo $var
回答by cokedude
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 }'); kill -9 $VAR 2>/dev/null; unset VAR;
回答by Kenneth King
Try to create a variable coming from vault/Hashicorp, when using packer template variables, like so:
尝试创建来自 vault/Hashicorp 的变量,当使用 packer 模板变量时,如下所示:
BUILD_PASSWORD=$(vault read secret/buildAccount| grep ^password | awk '{print }')
echo $BUILD_PASSWORD
You can to the same with grep ^user
你可以与 grep ^user
回答by jim
anytime you see grep piped to awk, you can drop the grep. for the above,
任何时候您看到 grep 通过管道传输到 awk,您都可以删除 grep。对于上述,
awk '/^password/ {print }'
awk can easily replace any text command like cut, tail, wc, tr etc. and especally multiple greps piped next to each other. i.e
awk 可以轻松替换任何文本命令,如 cut、tail、wc、tr 等,尤其是多个彼此相邻的 grep。IE
grep some_co.mand | a | grep b ... to | awk '/a|b|and so on/ {some action}.