2

I am having the following structure(only one row)

col1  col2  col3  col4
----------------------
12    34    14    10

what I have to do is I have to fetch col2 and col4 and used that value in shell.

a=$(awk 'NR<2{$2}')
b=$(awk'NR<2{$4}')

and I have to use a and b in my shell scripting. but this is not a good idea as I am using awk two times instead I am fetching value like this .

awk'NR<2{ a=$2;b=$4}'

but I dont know how can I use this a and b in my shell.

3 Answers 3

4

with eval you could assign more shell variables in one awk command. see the test below:

kent$  echo $a,$b
,

kent$  cat test
col1  col2  col3  col4
----------------------
12    34    14    10

kent$  eval $(awk 'NR==3{print "a="$2;print "b="$4}' test)

kent$  echo $a,$b
34,10

note that I just copied your input example, with header/titles etc. so in my script the data line is NR=3. you can adjust it if it is not in your case.

Sign up to request clarification or add additional context in comments.

1 Comment

Don't use eval unless it's absolutely necessary, which in this case it's not.
1

The read built-in is useful here.

read _ a _ b _ < <( tail -n +3 data.txt)  # Assign the columns you don't care about to _
echo $a,$b

This avoids the use of eval, which should generally be avoided if you can find another option.

Comments

0
$ v=( $(awk 'NR==3{print $2 ORS $4}' file) )
$ a="${v[0]}"
$ b="${v[1]}"
$ echo "$a,$b"
34,10

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.