0

I have a text file "a.txt", it is a 3X4 matrix, the structure is as follows:

1 apple 50 Mary
2 banana 40 Lily
5 orange 34 Jack

I want to extract the value "40" (Row 2, Col 3) and assign it to a new variable called "price".

I tried this:

awk 'NR == 2 {print $3}' a.txt > price
echo "$price"

But why the result is:

0

How can I solve this problem? Thank you.

2

To store the output of a command in a variable, use :

variable=$( commandFooBar )

Check HERE

  • Thank you. It works. price=$(awk 'NR == 2 {print $3}' a.txt); echo $price – lightsnail Sep 13 '16 at 21:14
  • Yes, but without the spaces around = – Gilles Quenot Sep 13 '16 at 21:15
  • O, yes! Thank you. Otherwise, the price will be detected as a command – lightsnail Sep 13 '16 at 21:17
  • 1
    You resource is actually better than tldp. Thanks again! @Gilles Quenot – lightsnail Sep 13 '16 at 21:20
2

You are mixing up two different shell operators.

The > redirect, will redirect output to a file. So to get your example to work, you could use:

awk 'NR == 2 {print $3}' a.txt > price
cat price   # display contents of file named price

The $ refers to a variable, so to get your echo to print out the variable, you would first have to set it from the output of the previous. Like so:

price=$(awk 'NR == 2 {print $3}' a.txt)
echo "$price"
  • Great! Really helpful! Thank you so much! – lightsnail Sep 14 '16 at 13:26
-1

The value isn't stored in variable but stored in a file named 'price'. Hence echo will not show a value. Try vim price.

  • How will this help the OP assign a value to a variable? – roaima Feb 11 at 14:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.