Manasa J
Manasa J

Reputation: 37

concatenate two variables from 2 different awk commands in a single echo

Job = grep 'Job:' | awk '{ print $3 }'
Status = grep 'Job Status:' | awk '{ print $3 }'

Both the variables are printed correctly by using two echo statements.I want a result like Job name - status in a single line.I have tried below commands. But its printing only 2nd variable like - status

echo "$Job - $Status"
echo "${Job} - ${Status}"
echo -e "${Job} - ${Status}"

please help!

Upvotes: 1

Views: 1144

Answers (3)

Mark Setchell
Mark Setchell

Reputation: 207395

I think you are trying to find out how to get the result of running some command and store it in a variable. Then you want to do that twice and print both variables on the same line.

So the basic syntax is:

result=$(some command)

e.g. if

date +'%Y'

tells you the year is 2014, but you want 2014 in a variable called year, you can do

year=$(date +'%Y')

then you can echo $year like this:

echo $year
2014

So, coming to your actual question, you want two variables, one for the output of each of two commands:

job=$(grep "Job:" someFile | awk '{print $3}')
status=$(grep "Job Status:" someFile | awk '{print $3}')

then you can do:

echo $job $status

and get both things on the same line.

The other answers are saying you can avoid invoking awk twice, which is true, but doesn't explain how to capture the result of running a command into a variable. In general, you don't need to use awk and grep, because this:

grep xyz | awk ...

is equivalent to

awk '/xyz/ {...}'

but uses one fewer processes (i.e. no grep) and therefore fewer resources.

And by the way, you must not put any spaces either side of = in bash either. It is

variable=something

not

variable = something

Upvotes: 0

martin
martin

Reputation: 3239

I think that should work:

echo  $(awk ' /Job:/ { print $3} ' file)" - "$(awk ' /Job Status:/ { print $3} ' file)

but konsolebox's version is probably better, as there is only one awk invocation.

Upvotes: 1

konsolebox
konsolebox

Reputation: 75458

You can do it with a single awk command:

awk '/Job:/ { job = $3 } /Job Status:/ { status = $3 } END { print job " - " status }' file

If Job: comes before Job Status:

awk '/Job:/ { job = $3 } /Job Status:/ { print job " - " $3; exit }' file

Or vice versa:

awk '/Job Status:/ { status = $3 } /Job Status:/ { print $3 " - " status; exit }' file

Upvotes: 1

Related Questions