1

I want to rename below files as follows.

Original files : 
x.1.gz
y.1.gz

Rename it to

x.dateTime.gz
y.dateTime.gz

I am using following script to do the same. But it is deleting files instead of renaming.

for file in *.1.gz; do
    mv "$file" "$($(date +’%Y%m%d%H%M’) "$file" .1.gz).gz"
done
1
  • How about this : rename 1 date +%Y%m%d%H%M *.gz Commented Apr 16, 2018 at 11:02

1 Answer 1

3

You can try the following:

for i in *.1.gz; do mv "$i" "$(basename $i .1.gz).$(date +'%Y%m%d%H%M').gz"; done

basename will extract the first part of the filename.

Note that the date command is using single quote ' and not the one you put on your question.

5
  • 3
    You can skip basename altogether with ${i%.1.gz}. Commented Apr 16, 2018 at 11:33
  • This works in command line. But when I am using in script, It is giving me error as : mv can not stat file, because we are using *. any solution for that ? Commented Apr 16, 2018 at 14:15
  • @KrunalParmar The error you get is unlikely to happen because if the file would not be there (can not stat file), globbing would not occur and the for loop would not execute, and so mv would also not start. If you have this error, there must be something fishy with your file or directory structure. Commented Apr 16, 2018 at 14:32
  • @oliv File is there. I am able to run the same line from command prompt. What I think is, It is taking *.1.gz as a file name and not taking * as a wildcard while using via script. Commented Apr 16, 2018 at 14:36
  • @KrunalParmar If you put this line in a script and you don't run this one from the folder where are located the files, then change the for loop by adding the path to your folder, e.g /path/to/my/folder/*.1.gz Commented Apr 17, 2018 at 5:42

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.