Piping a bash variable into awk and storing the output
To illustrate my problem,
TEST="Hi my name is John"
OUTP=`echo $TEST | awk '{print $3}'`
echo $OUTP
What I would expect this to do is pass the $TEST variable into awk and store the 3rd word into $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!
#!/bin/bash
TEST="Hi my name is John"
set -- $TEST
echo $3
#!/bin/bash
TEST="Hi my name is John"
var=$(echo $TEST|awk '{print $3}')
echo $var
In one line :
echo $(echo "Hi my name is John" | awk '{print $3}')
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 $3}'`
[bloom@little-cat-a ~]$ echo $OUTP
name
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.
One way to reproduce similar behavior:
$ alias echo='echo;'
$ echo Hi
Hi: command not found
$ alias
alias echo='echo;'
$ unalias echo
$ echo Hi
Hi
精彩评论