How can I use grep to search for years from 1900 to 2100?

advertisements

How can I use grep to search for years from 1900 to 2100?

For example, if I have a variable with 20123320 I want to print 2012.


Funny ways using bash (sh users beware!):

If you want to match and print all these years that appear at the beginning of lines in a file file:

printf "^%s\n" {1900..2100} | grep -of - file

If you have a variable variable that contains 20123320:

variable=20123320
printf "^%s\n" {1900..2100} | grep -of - <(echo "$variable")

Now please detail a little bit more what you want to do exactly so that we can give you the most appropriate answer.

Edit. As I see other answers using other tools than bash and grep here's a 100% bash solution:

variable="20123320"
# take the first 4 characters of variable:
year="${variable:0:4}"
# check that year is an integer and that it falls into the given range
if [[ "$year" =~ ^[[:digit:]]+$ ]] && (( 1900<=year && year<=2100)); then
    echo "$year"
else
    # Do whatever you want here
    echo "You dumbo, I couldn't find a valid year in your string"
fi