Appending time stamp for multiple file

Hi All,

I am trying to append time stamp to all file with wild character.

If you look above I want take all file with wild card *001* and append current time stamp to it.

I did below code. But not sure if there is any easy way that can be done in a single step

a=date +%s
for i in $(ls -l  *_001*); do
 mv $i $i_$a
done

Thanks
Arun

Without knowing what operating system and shell you're using we might be able to make lots of suggestions that can't possibly work in your environment.

Setting a the way you are gives it a value that is the literal string date +%s ; not to a value that is the output produced by running that date command. Using the ls command substitution is unnecessary, slows down your script, makes it vulnerable to failure in directories with lots of files or with lots of long filenames, and will fail when given filenames containing IFS characters. Consider replacing your script with:

a=$(date +%s)
for i in *_001*
do	mv "$i" "$i_$a"
done

to get rid of those problems.

1 Like

Thanks for your reply. I am using redhat linux and trying to do it in shell script . If there is a one liner awk or sed it will be very helpfull

I have given you a four line shell script that you can easily convert to a one line shell script if you want to make it harder to read, harder to understand, and harder to maintain. I much prefer to write code that is easier to read, easier to understand, and easier to maintain. Adding awk or sed to this script is certainly something you can do if you want to make this script run slower. But, of course, you still haven't told us what shell you're using, so the code I suggested could just give you a syntax error instead of doing anything at all close to what you want.

If you're using a shell that meets the requirements for the sh utility specified by the POSIX standard, you could modify the code I suggested to use awk , cat , cp , ed , ex , pr , sed , and probably several other utilities to copy your input files to the new names and then use rm or unlink to remove the old names (copying the data instead of just renaming the files, breaking links instead of maintaining them, and failing terribly for files that are not regular files instead of working for all file types). You could use pax to rename files while copying them. And, since you're on a system with GNU utilities, your best bet would probably be to try using the rename utility.

If rename won't work for you, you need to come up with a very good explanation as to why you would want to use awk or sed to move files instead of using the mv utility whose sole purpose is to move files.

1 Like