Linux 将 awk 输出保存到变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18648345/
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
Saving awk output to variable
提问by Jeremy
Can anyone help me out with this problem?
谁能帮我解决这个问题?
I'm trying to save the awk output into a variable.
我正在尝试将 awk 输出保存到一个变量中。
variable = `ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", }'`
printf "$variable"
EDIT: $12 corresponds to a parameter running on that process.
编辑:$12 对应于在该进程上运行的参数。
Thanks!
谢谢!
采纳答案by wens
#!/bin/bash
variable=`ps -ef | grep "port 10 -" | grep -v "grep port 10 -" | awk '{printf }'`
echo $variable
Notice that there's no space after the equal sign.
请注意,等号后没有空格。
You can also use $()
which allows nesting and is readable.
您还可以使用$()
which 允许嵌套并且可读。
回答by NiKiZe
I think the $() syntax is easier to read...
我认为 $() 语法更容易阅读......
variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", }')
But the real issue is probably that $12
should not be qouted with ""
但真正的问题可能是$12
不应该用“”来解决
Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef
is and what is expected in variable.
由于问题已更改而进行编辑,这将返回有效数据,但尚不清楚预期的输出ps -ef
是什么以及变量中的预期是什么。
回答by georgey
as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.
如前所述,设置 bash 变量不允许在 LHS 上的变量名称和 RHS 上的变量值之间存在空格,即“=”符号。
awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:
awk 可以做任何事情并避免“awk”病房额外的“grep”。awk 的 printf 的使用是为了不在字符串中添加不必要的“\n”,这会给 perl-ish 匹配器程序造成混淆。您在 bash 中的情况的变量/参数扩展没有这个问题,因此以下任一方法都有效:
variable=$(ps -ef | awk '/port 10 \-/ {print }')
variable=`ps -ef | awk '/port 10 \-/ {print }'`
The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.
'-' int awk 记录匹配模式消除了从搜索结果中删除 awk 本身的需要。
回答by Jotne
variable=$(ps -ef | awk '/[p]ort 10/ {print }')
The [p]
is a neat trick to remove the search from showing from ps
这[p]
是从显示中删除搜索的巧妙技巧ps
@Jeremy
If you post the output of ps -ef | grep "port 10"
, and what you need from the line, it would be more easy to help you getting correct syntax
@Jeremy 如果您发布 的输出ps -ef | grep "port 10"
以及您需要的内容,那么帮助您获得正确的语法会更容易