I am kind of stuck in a tricky situation. I have a file, whose contents look like this:

3               2017-05-30      2017-09-29
2               2017-05-27      2017-08-26
1               2017-05-27      2017-08-26

Now, user selects to modify a date by choosing labelNum which would be values in column 1. Upon prompt, if user enters 3. I want to print column 2.

So I wrote.

cat temp.txt | grep $labelNum | awk '{print $2}'

If labelNum is 3, I get the output as 2017-05-30

But, if user enters labelNum as 2, then i get:


Because it is looking for '2' everywhere in the .txt file. However, I want the column 2 for labelNum 2, which would be 2017-05-27

Is there a way to do this? I tried using awk to replace grep but no luck.


Edit: The rows are dynamic and can change as and when more entries are added to text file. So can't really use sed to skip to the line

2 Answers 2


With single awk:

awk -v lbl=$labelNum '$1 == lbl{ print $2 }' temp.txt

  • -v lbl=$labelNum - passing in labelNum variable value into awk script

  • $1 == lbl - if the 1st column value equal to the variable value - executes the followed expression


You also can stay around your solution:

cat temp.txt | grep ^$labelNum | awk '{print $2}'

Which will match at the beginning of the line, or

awk '/^'$labelNum'/{print $2}' temp.txt

Would work alike, but the escaping is tricky inside of awk.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .