[英]Script to remove spaces in all files and folders?
I wrote a script which removes spaces in a single folder/file name.我编写了一个脚本,用于删除单个文件夹/文件名中的空格。 I want to make it work so that it removes all spaces in folder/files name in the directory the script exists.
我想让它工作,以便它删除脚本存在的目录中文件夹/文件名中的所有空格。
MY Script:我的脚本:
#!/bin/bash
var=$(ls | grep " ")
test=$(echo $var | sed 's/ //')
mv "$var" $test
Thank you for helping!感谢您的帮助!
Try this尝试这个
ls | grep " " | while read file_name
do
mv "$file_name" "$(echo $file_name | sed -E 's/ +//g')"
done
sed -E
is so that you can use some simple regex, and / +/
so it can work in case of multiple consecutive spaces such as sed -E
是为了让你可以使用一些简单的正则表达式,并且/ +/
所以它可以在多个连续空格的情况下工作,例如
. . And
/g
so it replaces every occurrences such as foo baa.txt
.和
/g
所以它会替换所有出现的地方,例如foo baa.txt
。
Something like this might work:像这样的东西可能会起作用:
for f in * ; do
if [[ "$f" =~ \ ]] ; then
mv "$f" "${f// /_}"
fi
done
Explanattion:解释:
for f in * ; do
loops over all file names in the directory.循环遍历目录中的所有文件名。 It doesn't have the quirks of
ls
that make parsing the output of ls
a bad idea.它没有
ls
的怪癖,使解析ls
的 output 成为一个坏主意。
if [[ "$f" =~ \ ]] ; then
This is the bash
way of pattern matching.这是模式匹配的
bash
方式。 The \
is the pattern. \
是模式。 You need to escape the space with a backslash, otherwise the shell will not recognize it as a pattern.您需要使用反斜杠转义空格,否则 shell 将无法将其识别为模式。
mv "$f" "${f// /_}"
${f// /_}
is the bash
way of pattern-substitution. ${f// /_}
是模式替换的bash
方式。 The //
means replace all occurrences. //
表示替换所有匹配项。 The syntax is ${variable//pattern/replacement}
to replace all patterns in the variable with the replacement.语法是
${variable//pattern/replacement}
用替换替换变量中的所有模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.