Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

TDKR(2012)    
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
add comment

3 Answers

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. –  Stephane 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. –  Stephane 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
add comment

With perl:

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

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

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

Your Answer

 
discard

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.