将 bash 变量传送到 awk 并存储输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2489856/
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
Piping a bash variable into awk and storing the output
提问by Andrew Smith
To illustrate my problem,
为了说明我的问题,
TEST="Hi my name is John"
OUTP=`echo $TEST | awk '{print }'`
echo $OUTP
What I would expect this to do is pass the $TEST variable into awk and store the 3rd word into $OUTP.
我希望这样做是将 $TEST 变量传递到 awk 并将第三个字存储到 $OUTP 中。
Instead I get "Hi: not found", as if it is expecting the input to be a file. If I pass just a string instead of a variable, however, there is no problem. What would be the best way to approach this?
相反,我得到“嗨:未找到”,就好像它期望输入是一个文件。但是,如果我只传递一个字符串而不是变量,则没有问题。解决这个问题的最佳方法是什么?
Thanks all!
谢谢大家!
回答by ghostdog74
#!/bin/bash
TEST="Hi my name is John"
set -- $TEST
echo
#!/bin/bash
TEST="Hi my name is John"
var=$(echo $TEST|awk '{print }')
echo $var
回答by bobylapointe
In one line :
在一行中:
echo $(echo "Hi my name is John" | awk '{print }')
回答by Ken Bloom
Your code works for me, as-is.
您的代码按原样对我有用。
[bloom@little-cat-a ~]$ TEST="Hi my name is John"
[bloom@little-cat-a ~]$ OUTP=`echo $TEST | awk '{print }'`
[bloom@little-cat-a ~]$ echo $OUTP
name
回答by Isaac
As with others, this works for me as-is, but perhaps adding double-quotes ("
) around $TEST
in line 2 would help. If not, more specific information about the system on which you are running bash might help.
与其他人一样,这按原样对我有用,但也许在第 2 行中添加双引号 ( "
)$TEST
会有所帮助。如果没有,有关运行 bash 的系统的更多具体信息可能会有所帮助。
回答by Paused until further notice.
One way to reproduce similar behavior:
重现类似行为的一种方法:
$ alias echo='echo;'
$ echo Hi
Hi: command not found
$ alias
alias echo='echo;'
$ unalias echo
$ echo Hi
Hi