1

I have similar different file of the format backup_2016-26-10_16-30-00 is it possible to rename using bash script to backup_26-10-2016_16:30:00 for all files. Kindly suggest some method to fix this.

Original file:

backup_2016-30-10_12-00-00

Expected output:

backup_30-10-2016_12:00:00

4 Answers 4

3

To perform only the name transformation, you can use awk:

echo 'backup_2016-30-10_12-00-00' | awk -F'[_-]' '{ print $1 "_" $3 "-" $4 "-" $2 "_" $5 ":" $6 ":" $7 }' 

As fedorqui points out in a comment, awk's printf function may be tidier in this case:

echo 'backup_2016-30-10_12-00-00' | awk -F'[_-]' '{ printf "%s_%s-%s-%s_%s:%s:%s\n", $1,$3,$4,$2,$5,$6,$7 }' 

That said, your specific Linux distro may come with a rename tool that allows you to do the same while performing actual file renaming.

Sign up to request clarification or add additional context in comments.

1 Comment

That was so perfect :)
3

with perl based rename command:

$ touch backup_2016-30-10_12-00-00 backup_2016-26-10_16-30-00 $ rename -n 's/(\d{4})-([^_]+)_(\d+)-(\d+)-/$2-$1_$3:$4:/' backup* rename(backup_2016-26-10_16-30-00, backup_26-10-2016_16:30:00) rename(backup_2016-30-10_12-00-00, backup_30-10-2016_12:00:00) 

remove the -n option for actual renaming

Comments

2

rename is for this task

$ rename 's/_(\d{4})-(\d\d-\d\d)_(\d\d)-(\d\d)-(\d\d)$/_$2-$1_$3:$4:$5/' backup_2016-30-10_12-00-00 

but not sure will be simpler

Comments

1

you can also this script;

#!/bin/bash fileName=$1 prefix=$(echo ${fileName} | cut -d _ -f1) date=$(echo ${fileName} | cut -d _ -f2) time=$(echo ${fileName} | cut -d _ -f3) year=$(echo ${date} | cut -d - -f1) day=$(echo ${date} | cut -d '-' -f2) month=$(echo ${date} | cut -d '-' -f3) formatedTime=$(echo $time | sed 's/-/:/g') formatedDate=$day"-"$month"-"$year formatedFileName=$prefix"_"$formatedDate"_"$formatedTime echo $formatedFileName 

Eg;

user@host:/tmp$ ./test.sh backup_2016-30-10_12-00-00 backup_30-10-2016_12:00:00 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.