Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm new to Linux. I've a file which contains list of movie names and their release year. I want to list out all release years. Specifically my file looks like below

Vicky Cristina Barcelona (2008)  

I tried grep with regex as follows

grep "^.*\\([0-9]*\\)$" movie.txt

and it works but it is printing entire line I want only years. Can I do it with grep?

share|improve this question
up vote 3 down vote accepted

GNU grep supports an -o option which will give you the matching pattern, so you could use grep -o '([0-9]\+)' but this will also print the parentheses. For more flexibility and portability, though, you should post-process with sed:

grep '([0-9]\+)$' movie.txt | sed 's/.*(\([0-9]\+\))$/\1/'
# assumes that the year is always at the end of the line.
share|improve this answer
Well, grep being a subset of sed, there's no need for grep here (also note that \+ in sed is not portable nor standard). sed -n 's/.*(\([0-9]\{1,\}\)).*/\1/p'. All those assume there's only one occurrence of (xxx) per line. – Stéphane Chazelas Oct 22 '12 at 19:09
@sch I don't have it in front of me to test, without grep will this filter out lines that don't match the pattern at all? – Random832 Oct 22 '12 at 20:20
Yes, -n is to not print the line by default, and the p flag to the s command is to print the line when the substitution is successful. – Stéphane Chazelas Oct 22 '12 at 21:22
With GNU grep, you can use Perl regex syntax: grep -Po '(?<=\()[0-9]+(?=\))' but it doesn't exactly roll off the tongue. – Gilles Oct 22 '12 at 22:12

If the numbers are always the last field, then you can do it with a single awk command.

bash$ awk '{gsub(/\(|\)/," "); print $NF};' $file
share|improve this answer

With perl:

perl -lne 'print for /\((\d+)\)/g'
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.