Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Piping a bash variable into awk and storing the output

Tags:

bash

awk

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!

like image 641
Andrew Smith Avatar asked Mar 22 '10 03:03

Andrew Smith


People also ask

How do you store output of awk in a variable?

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.

Can you pipe to a variable in bash?

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.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.


2 Answers

#!/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
like image 114
ghostdog74 Avatar answered Sep 21 '22 15:09

ghostdog74


In one line :

echo $(echo "Hi my name is John" | awk '{print $3}')
like image 37
bobylapointe Avatar answered Sep 24 '22 15:09

bobylapointe