Skip to content
Advertisement

GREP to search for second column in a text file

I need to GREP second column (path name) from the text file. I have a text file which has a md5checksum filepath size . Such as:

ce75d423203a62ed05fe53fe11f0ddcf kart/pan/mango.sh 451b
8e6777b67f1812a9d36c7095331b23e2 kart/hey/local 301376b
e0ddd11b23378510cad9b45e3af89d79 yo/cat/so 293188b
4e0bdbe9bbda41d76018219f3718cf6f asuo/hakl 25416b

the above is the text file, I used grep -Eo '[/]' file.txt but it prints only / , but i want the output like this:

kart/pan/mango.sh
kart/hey/local
yo/cat/so
asuo/hakl

Lastly I have to use GREP.

Advertisement

Answer

If you can live with spaces before and after, you can use:

grep -o "s[[:alnum:]/]*s"

If you need the spaces removed, you will need some zero-width look-ahead/look-behind which is only available with -P (perl regexes), if you have that you can use:

grep -Po "(?<=s)[[:alnum:]/]+(?=s)"
  • (?<=s) – look-behind to see if there is a space preceding the string, but not capture it
  • (?=s) – look-ahead to see if there is a space after the match, but not capture it
  • [:alnum:] – match alpha numeric chars
  • [[:alnum:]/] – match alphanumeric chars and /
  • + – match one or more

However, grep is not the right tool for this, cut/sed/awk are way better

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement