Rename multiple files

Hi,

In my directory I have many files, for e.g.

file_123
file_124
file_125
file_126
file_127

Instead of renaming these files one by one, I would like to rename them at a same time using same command... they should appear like

123
124
125
126
127

What command(awk or ls or anything...) should work here?

regards,
juzz4fun

The simple thing is to just use bash, ksh, or any other POSIX conforming shell (I used ksh for this example):

#!/bin/ksh
for i in file_*
do      echo mv "$i" "${i#file_}"
done

if the commands printed are what you are trying to do, remove the "echo " so the script will actually move the files. With the files in the current directory you listed, the output produced is:

mv file_123 123
mv file_124 124
mv file_125 125
mv file_126 126
mv file_127 127
1 Like

Thanks a ton... :slight_smile:

By the way, I guess ${i#"...."} removes the string in double quotes...what if I want to add some string... like

folder_123
folder_124
folder_125
folder_126
folder_127

regards,
juzz4fun

I'm not sure I understand your question. If you man you want to move file_123 to folder_123 and instead of just removing file_ , try:

#!/bin/ksh
for i in file_*
do      mv "$i" "folder${i#file}"
done

The expansion of ${i#string} removes string from the start of the expansion of $i if the expansion of $i starts with string ; otherwise, it just results in the expansion of $i . (If string contains filename pattern matching special characters it is more complex than that, but in this case there are no special characters in the pattern.)

1 Like