Find lines where column starts with a string

Viewed 41

I need to find lines in the text file where the second column starts with the number 117. How do I do that in bash? I tried

grep -E 117 test.txt

but that just prints everything with 117.

2 Answers

If you want to use , make sure that you match the second column:

grep -E '^\w+\s+117' test.txt
  • -E use extended regular expressions
  • ^ start of the line anchor
  • \w+ one or more characters
  • \s+ one or more whitespaces
  • 117 match when the second column starts with the number 117

grep is not the right tool for this. Use one of these 2 awk solutions:

# regex approach
awk '$2 ~ /^117/' test.txt

# non-regex approach
awk 'index($2, "117") == 1' test.txt
Related