Bash – Don’t need the whole line, just the match from regular expression

bashgrepregexshell

I simply need to get the match from a regular expression:

$ cat myfile.txt | SOMETHING_HERE "/(\w).+/"

The output has to be only what was matched, inside the parenthesis.

Don't think I can use grep because it matches the whole line.

Please let me know how to do this.

Best Answer

2 Things:

  • As stated by @Rory, you need the -o option, so only the match are printed (instead of whole line)
  • In addition, you neet the -P option, to use Perl regular expressions, which include useful elements like Look ahead (?= ) and Look behind (?<= ), those look for parts, but don't actually match and print them.

If you want only the part inside the parenthesis to be matched, do the following:

grep -oP '(?<=\/\()\w(?=\).+\/)' myfile.txt

If the file contains the sting /(a)5667/, grep will print 'a', because:

  • /( are found by \/\(, but because they are in a look-behind (?<= ) they are not reported
  • a is matched by \w and is thus printed (because of -o )
  • )5667/ are found by \).+\/, but because they are in a look-ahead (?= ) they are not reported
Related Topic