How to replace a string in all file names in a directory? (in particular, I need to remove "\ # 015" from all the file names in the directory

Many files in the directory ( /root/path/ ) have a strange string of characters added to them ( \#015 ). Help me replace them with ordinary names without a weird string.

I need:

 /root/path/img1.png\#015 /root/path/img2.jpg /root/path/img3.png\#015 

To be:

 /root/path/img1.png /root/path/img2.jpg /root/path/img3.png 

You can help?

+6
source share
4 answers
 for file in *\#015 do mv -- "$file" "${file%\#015}" done 

You may need to avoid the "\" s. First try in the tmp directory.

+5
source

If you have rename installed, this becomes a fairly simple task:

 rename 's/\\#015$//' /root/path/*\\#015 

You can add the -f flag to force overwrite existing files.

+5
source

This is how I solved a similar problem in the past with a small shell.

 cd /root/path/ ls | grep '\#015' | sed 's/\(.*\)\\#015/mv & \1/' | sh 
+1
source

You can do this with find and parameter substitution as follows:

 #!/bin/bash find -name '*\\#015' | while IFS= read -rf do mv -- "${f}" "${f%?????}" done 
  • Put the above code in a script called my_script.sh in /root/path/ and run it chmod +x my_script.sh && ./my_script.sh
  • Note that this will apply the changes recursively to all subfolders in /root/path/ .

Explanation:

  • find -name '*\\#015' : find all files ending in \#015
  • Then for each file found: mv "${f}" "${f%?????}" renames it from the old name to the new name with the last 5 characters in the deleted file name.
0
source

All Articles