Grep match only before “:”

2020-05-08 00:46发布

问题:

Hello How can I grep only match before : mark?

If I run grep test1 file, it shows all three lines.

test1:x:29688:test1,test2
test2:x:22611:test1
test3:x:25163:test1,test3

But I would like to get an output test1:x:29688:test1,test2

I would appreciate any advice.

回答1:

If the desired lines always start with test1 then you can do:

grep '^test1' file

If it's always followed by : but not the other (potential) matches then you can include it as part of the pattern:

grep 'test1:' file


回答2:

As your data is in row, columns delimited by a character, you may consider awk:

awk -F: '$1 == "test1"' file


回答3:

I think that you just need to add “:” after “test1”, see an example:

grep “test1:” file


标签: grep