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?


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.
  • 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 'SO- stop being evil' 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

With perl:

perl -lne 'print for /\((\d+)\)/g'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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