Date Arithimetic in shell scripts

Hi,

I have a file which has a date extension to it.
Like <filename>_01012014.

I need to rename the file as 12152013 , that is i need to be able to subtract 15 days from the date of the file name.

Please advise how this can be handled using shell scripting.

Regards,
VN

$ cat tester
#!/bin/bash

file="filename_01012014"
touch $file
cp $file "${file%%_*}_"$(date -d"$(sed -r 's/(.{2})(.{2})(.{4})/\3\2\1/' <<<"${file##*_}") -15 days " +"%d%m%Y")
$ bash tester
$ ls filename_* -1
filename_01012014
filename_17122013

if happy replace cp with mv

for multiple files try this

#!/bin/bash

for file in filename_*; do
cp $file "${file%%_*}_"$(date -d"$(sed -r 's/(.{2})(.{2})(.{4})/\3\2\1/' <<<"${file##*_}") -15 days " +"%d%m%Y")
done

Tested with

GNU sed version 4.2.1
date (GNU coreutils) 8.13
GNU bash, version 4.2.25(1)-release (i686-pc-linux-gnu)
1 Like

I'm using korn shell.

sh tester
tester: syntax error at line 4: `(' unexpected

Please advise

use ksh <scrptname>

Thanks for your inputs.

ksh tester
tester[4]: syntax error at line 1 : `<' unexpected

I still get an error

The problem appears to be GNU date. That is generally available on Linux servers, not other kinds of UNIX. What UNIX are you running the script on?

Oracle Solaris and am using korn shell

Refer thread: Date Arithmetic

I wrote a limited substitute for gnu date in perl.