Search code examples
linuxshellgrepshcut

grep command not working as my expectation


I have a text file like mentioned below, and along with that I will pass an input for which I want a corresponding output.

Input file: test.txt

abc:abc_1
abcd:abcd_1
1_abcd:1_abcd_bkp
xyz:xyz_2

so if I use abc with the above test.txt file, I want abc_1; and if I pass abcd, I need abcd_1 as output.

I tried cat text.txt | grep abc | cut -d":" -f2,2, but I am getting the output

abc_1
abcd_1
1_abcd_bkp

when I want only abc_1.


Solution

  • With GNU grep:

    grep -Po "^abc:\K.*" file
    

    Output:

    abc_1
    

    \K keeps the text matched so far out of the overall regex match.