Need to rename all files in a directory using Linux shell? If so, this short article is exactly for you. All situations will be explained with example and explanation:
- Add suffix or prefix to all files in folder
- Replace spaces with underscores
- change file names from Upper case to Lower
P.S. All examples assume that terminal is opened with the directory where the files are stored! If not you can do it by: cd /home/user
or you can check the working folder by: pwd
Add suffix or prefix to all files in folder
In this example there are many files in a folder which doesn't have any extension. The goal is to update all files and add an extension as suffix. This can be done by next example:
for f in *; do
mv "$f" "${f%}.txt"
done
result:
my file name -> my file name.txt
Explanation:
- List all files in the current folder - the
*
matches any file. You can list all files by pattern like:*.txt
orsong_*
- Next line
mv "$f" "${f%}.txt"
add.txt
as suffix to all files
The same logic applies if you need to add prefix or both.
Replace spaces with underscores for Linux files
Linux and some applications "doesn't like" spaces in files names. For example if you try to open a file by a command like: xed $file
and the file contain spaces: my file name
. You will end by xed opening: my, file and name or equivalent of: xed my, xed file, xed name. In order to avoid this you can replace all spaces from your file names by
find $1 -name "* *.txt" -type f -print0 | \
while read -d $'\0' f; do
mv -v "$f" "${f// /_}";
done
result:
my file name.txt -> my_file_name.txt
Explanation:
- List all text files with spaces (or change the pattern) in the current folder
- line
mv -v "$f" "${f// /_}";
is replacing all spaces find in the name by underscores by this pattern:${f// /_}
Replace spaces with underscores for Linux files
Some websites and applications works with file names only in upper or lower case. In order to change the file name from any case to lower case only you can use next script:
for i in $( ls | grep [A-Z] ); do
mv -i $i `echo $i | tr 'A-Z' 'a-z'`;
done
result:
My_file_name.txt -> my_file_name.txt
Explanation:
ls | grep [A-Z]
- this command will list all files and folders and will match only uppercase letters.- statement
mv -i $i
echo $i | tr 'A-Z' 'a-z';
will do the replacement for upper to lower case.
Note that last command might not work in cases of spaces in the file names.