Linux - Replacing spaces in the file names

2019-03-07 13:50发布

I have a number of files in a folder, and I want to replace every space character in all file names with underscores. How can I achieve this?

11条回答
来,给爷笑一个
2楼-- · 2019-03-07 14:29

Quote your variables:

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

Remove the "echo" to do the actual rename.

查看更多
Luminary・发光体
3楼-- · 2019-03-07 14:30

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.

查看更多
做个烂人
4楼-- · 2019-03-07 14:33

This should do it:

for file in *; do mv "$file" `echo $file | tr ' ' '_'` ; done
查看更多
放我归山
5楼-- · 2019-03-07 14:33

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
查看更多
Anthone
6楼-- · 2019-03-07 14:33
姐就是有狂的资本
7楼-- · 2019-03-07 14:35

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.

查看更多
登录 后发表回答