Linux - Replacing spaces in the file names

断了今生、忘了曾经 提交于 2019-12-02 13:53:06
neesh

This should do it:

for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done

I prefer to use the command 'rename', which takes Perl-style regexes:

rename "s/ /_/g" *

You can do a dry run with the -n flag:

rename -n "s/ /_/g" *

Use sh...

for i in *' '*; do   mv "$i" `echo $i | sed -e 's/ /_/g'`; done

If you want to try this out before pulling the trigger just change mv to echo mv.

What if you want to apply the replace task recursively? How would you do that?

Well, I just found the answer myself. No the most elegant solution (tries to rename also files that do not comply with the condition) but works. (BTW, in my case I needed to rename the files with '%20', not with an underscore)

#!/bin/bash
find . -type d | while read N
do
     (
           cd "$N"
           if test "$?" = "0"
           then
               for file in *; do mv "$file" ${file// /%20}; done
           fi
     )
done

If you use bash:

for file in *; do mv "$file" ${file// /_}; done
ghostdog74

Quote your variables:

for file in *; do echo mv "'$file'" "${file// /_}"; done

Remove the "echo" to do the actual rename.

Amir Afghani

Try something like this, assuming all of your files were .txt's:

for files in *.txt; do mv “$files” `echo $files | tr ‘ ‘ ‘_’`; done

The easiest way to replace a string (space character in your case) with another string in Linux is using sed. You can do it as follows

sed -i 's/\s/_/g' *

Hope this helps.

Here is another solution:

ls | awk '{printf("\"%s\"\n", $0)}' | sed 'p; s/\ /_/g' | xargs -n2 mv
  1. uses awk to add quotes around the name of the file
  2. uses sed to replace space with underscores; prints the original name with quotes(from awk); then the substituted name
  3. xargs takes 2 lines at a time and passes it to mv
Arthur Frankel

I believe your answer is in Replace spaces in filenames with underscores.

To rename all the files with a .py extension use, find . -iname "*.py" -type f | xargs -I% rename "s/ /_/g" "%"

Sample output,

$ find . -iname "*.py" -type f                                                     
./Sample File.py
./Sample/Sample File.py
$ find . -iname "*.py" -type f | xargs -I% rename "s/ /_/g" "%"
$ find . -iname "*.py" -type f                                                     
./Sample/Sample_File.py
./Sample_File.py
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!