12 08 | 2013

grep --only-matching

Written by Tanguy

Classified in : Homepage, Debian, Command line, To remember

Magnifying glass over a sheet of text

grep is designed to print lines matching a given pattern, but I often need to print only the matching part, discarding the remaining.

I used to do that with sed, but it involves several actions: match, replace the line by only the matching pattern and print. Fortunately, GNU grep has an option to do just that:

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

Unfortunately it is not a standard option, so it may be missing on non-GNU systems.

Tags : grep, only, matching, option, sed, GNU

2 comments

monday 12 august 2013 à 14:02 Jeff Epler said : #1

cat <<'EOF' > printmatching.awk
#!/usr/bin/awk -f
{ if(match($0, expr)) print substr($0, RSTART, RLENGTH) }
EOF
chmod +x printmatching.awk

call as e.g.,
printmatching.awk -v expr="a.*a" printmatching.awk

I believe this is POSIX-compatible use of awk.

monday 12 august 2013 à 19:52 barmic said : #2

You can use : sed -n 's/.*\(expr\).*/\1/p'

Write a comment

What is the last letter of the word pydkda? : 

Archives