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!
Example -1: Defining and printing variable `awk` command uses '-v' option to define the variable. In this example, the myvar variable is defined in the `awk` command to store the value, “AWK variable” that is printed later. Run the following command from the terminal to check the output.
Piping read to assign a value to a variable, the shell creates a new sub-shell where the piped command is executed. Therefore, the value is lost, and the variable cannot be used. However, when we use the lastpipe option in the recent versions of bash, we can pipe the output of a command, such as echo, to read.
If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.
#!/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}')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With