我想要一个可以在linux上运行的脚本来重命名这个表单中的文件,即Yahoo Babel Fish - Persistent Cross Site Scripting Vulnerability.jpg到Yahoo-Babel-Fish-Persistent-Cross-Site-Scripting-Vulnerability.jpg
它只删除每个空格并用连字符更改它,如果它是两个空格之间的连字符,它只删除空格,就像你在这部分中看到的那样 “鱼 - 持久”到“鱼持久”
答案 0 :(得分:5)
如果您想处理当前目录中的每个文件,可以分两行进行:
for f in *; do mv "$f" "$(echo $f | sed 's/ /-/g')"; done
for f in *; do mv "$f" "$(echo $f | sed 's/---/-/g')"; done
可能有一种方法可以在一行中完成,但目前我无法想到它。
答案 1 :(得分:1)
这是一个利用bash数组和extglob功能的纯bash解决方案:
shopt -s extglob
oIFS="$IFS" # save the original IFS
for file in *.jpg; do # Or whatever pattern you like
target=( ${file//+(-)/ } ) # Break the filename into an array on spaces, after turning - into space.
IFS='-' # Temporarily set the internal field separator into a dash so we can join on dashes.
mv "$file" "${target[*]}"
IFS="$oIFS"
done
答案 2 :(得分:1)
for file in *.jpg ; do file2="${file// - /-}"; file2="${file2// /-}"; echo mv "$file" "$file2" ;done
如果你想要的话,删除回声。
答案 3 :(得分:0)
以下是我写这篇文章时存在的三个答案的一些基准。随意扩展:
$ ./rename_bench
setting up
timing ext
real 0m35.453s
user 0m6.006s
sys 0m27.417s
setting up
timing sed
real 1m17.498s
user 0m15.223s
sys 0m56.376s
setting up
timing straight
real 0m38.352s
user 0m6.028s
sys 0m28.254s
$ ./rename_bench
setting up
timing ext
real 0m36.234s
user 0m6.030s
sys 0m28.270s
setting up
timing sed
real 1m16.467s
user 0m15.277s
sys 0m56.194s
setting up
timing straight
real 0m33.538s
user 0m5.911s
sys 0m26.672s
实际的基准脚本:
#!/bin/bash
setup() {
cd $(mktemp -dt "foo") &&
touch 'a - '{0..10000}'buzz.jpg'
}
ext_rename() {
shopt -s extglob
oIFS="$IFS" # save the original IFS
for file in *.jpg; do # Or whatever pattern you like
target=( ${file//+(-)/ } ) # Break the filename into an array on spaces, after turning - into space.
IFS='-' # Temporarily set the internal field separator into a dash so we can join on dashes.
mv "$file" "${target[*]}"
IFS="$oIFS"
done
}
sed_rename() {
for f in *.jpg; do
mv "$f" "$(sed -e 's/ /-/g' -e 's/---/-/g' <<< "$f")"
done
}
straight_rename() {
for file in *.jpg; do
file2="${file// - /-}"
file2="${file2// /-}"
mv "$file" "$file2"
done
}
echo "setting up"
setup
echo "timing ext"
time ext_rename
echo "setting up"
setup
echo "timing sed"
time sed_rename
echo "setting up"
setup
echo "timing straight"
time straight_rename