I have a text file sort.txt, which has content something like this:

2 Jack
2 Naomi
2 Tina
1 John
1 Tyler

I want to print out all the lines that begin with 2, but the problem is the number might not always be 2, it can be any number. I just want to print all the lines who's first word is the same as the first line. So if the first word was 3, print out all the lines that start with 3. I tried doing this, but it didn't work:

firstWord=awk '{print $1;}'
egrep "^$firstWord" sort.txt
  • What about a line (for the example) that is: 22Jeff, or 22 Jeff? – Jeff Schaller Oct 31 '18 at 17:56
  • it would never have lines with that, because i already created sort.txt to have a space between all numbers – ash Oct 31 '18 at 18:10
  • Ok; I wanted to double-check, because your grep statement allows for "anything" following the "firstWord" -- at least, that's the direction it was going. Wanted to make sure the Answers followed what you intended. Thanks! – Jeff Schaller Oct 31 '18 at 18:11

It is pretty trivial with awk. Get the first word of first line in a variable and then for the subsequent lines, use that variable to match the first word and print only those lines

awk 'NR == 1 { fw = $1 } $1 == fw' sort.txt

The construct NR == 1 gets only the first line of the input file and there is no special de-limiters defined in each line (white-space de-limited), the first field is accessed by $1 and stored into fw. The later condition $1 == fw evaluates each lines and returns true only if the condition is satisfied, thereby printing the line.


Using awk:

awk 'NR == 1 { word=$1 } { if (match($0, "^"word) > 0) print }' < sort.txt

On the first line NR == 1, assign the "word" value to be the first word from the line.

On any line, if the line matches the variable word at the beginning of the line, print it.

  • I've reworked the awk statement to avoid the double-printing, and also more closely align with the "grep ^pattern" example. – Jeff Schaller Oct 31 '18 at 18:01

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.