n0zz
n0zz

Reputation: 327

Rename bunch of files in bash script

I have some files with names which contains date, but this date part is in wrong format, and I need to change it. Example files:

foo-1-21-01-16.tar
foo-1-22-01-16.tar
foobar-1-21-01-16.tar
foobar-1-22-01-16.tar

Result that I want to have should look like this:

foo-1-16-01-21.tar
foo-1-16-01-22.tar
foobar-1-16-01-21.tar
foobar-1-16-01-22.tar

So, what I want to do is to change place of "day" part with place of "year" part. But I can't figure out how to do this. There is more than a few files, so I can't do this manually.

Upvotes: 0

Views: 36

Answers (1)

Derlin
Derlin

Reputation: 9881

You would suggest you use AWK. Example:

  echo "foo-1-21-01-16.tar" | awk -F'[-.]' '{printf "bar-%s-%s-%s-%s.%s", $2, $5, $4, $3, $6 }'

will result in bar-1-16-01-21.tar. The -F parameter tells awk to split each line of input on - or .. After the split, $1 = foo, $5 = year, etc. use print to recompose a filename with each field in another order.

From a bash script, iterate through your files, use the above command to create the new filename, then use mv to rename the file. Tell me if you need a code example.

Upvotes: 1

Related Questions