1
votes

Convert a a two digit year to four digits in bash

I have files in the format: test96abcd.TXT I am extracting the two digit year:

echo "test96abcd.TXT" | cut -c4-5

and I was hoping to do something like this:

echo "test96abcd.TXT" | cut -c4-5 | date +%Y

but it doesn't work, let alone I will have a ...Y2K problem (when it is 00, won't know if it is year 1900 or year 2000) although I can handle manually this exception with an "if 00 use 2000".

But is there a more elegant way to deal with this using t he 'date' command?

1
Never mind 00s - how do you know if the date XX should EVER be 20XX vs 19XX or something else? if you just want to change every XX to 20XX then you don't need date for that. Do your files always have 2 digits and only 2 digits in just 1 location or can you get files like foo76bar83etc.txt or foo1234bar.txt and if so how should they be handled? - Ed Morton
I do know that my dates are from 1980-today (will not go beyond 2030) and they are consistently named as I described. I can do a long case statement but looking for a more elegant way... - G. D'Seas

1 Answers

0
votes
$ cat ../tst.sh
#!/bin/env bash

for old; do
    [[ $old =~ ^([^0-9]*)(([0-9]*).*) ]] || continue
    year=${BASH_REMATCH[3]}
    if (( year > 80 )); then
        cent='19'
    else
        cent='20'
    fi
    new="${BASH_REMATCH[1]}${cent}${BASH_REMATCH[2]}"
    mv -- "$old" "$new"
done

$ ls
test00abcd.txt  test17abcd.txt  test96abcd.txt

$ ../tst.sh *

$ ls
test1996abcd.txt  test2000abcd.txt  test2017abcd.txt