![](/img/trans.png)
[英]How to remove leading or trailing spaces in files, directories, and subdirectories using bash script?
[英]Remove leading and trailing whitespace directories
問題是Mac OS X允許文件夾獲取諸如" Foo Bar /"
類的名稱。
這是我自己可以解決的,並且可以解決大多數問題。
for d in */ ; do
echo "$d" | xargs
done
結果: "Foo Bar /"
。
唯一的問題是在目錄名和斜杠之間留出最后一個空格。
有人可以幫忙擺脫最后的空間嗎?
嘗試以下僅使用bash的方法:
dir="some dir /"
fixed=${dir/ \///}
echo $fixed
some dir/
重擊字符串操作:
開始刪除STRING :
${string#substring} - remove shortest substring match from beginning
${string##substring} - remove longest substring match from beginning
刪除STRING的結尾 :
${string%substring} - remove shortest matching substring from tail
${string%%substring} - remove longest matching substring from tail
替換 :
${string/substring/replacement} - replace first match of substring
${string//substring/greplacement} - replace all matches of substring
${string/#substring/replacement} - replace substring at front of string
${string/%substring/replacement} - replace substring at tail of string
像這樣使用sed怎么辦:
name=" Foo Bar /"
echo "$name" | sed 's/^\s*\(.*\)\s*$/\1/g' | tr -s ' '
sed表達式刪除名稱之前和之后的所有空格,而tr將其最多壓縮為1。
問題是Mac OS X允許文件夾獲取諸如“ Foo Bar /”之類的名稱。
這也是Unix / BASH問題。 文件名中除 NUL
和正斜杠以外的所有字符均為有效字符。 這包括控制字符,例如退格和UTF8字符。
您可以使用${WORD%%filter}
和${WORD##filter}
來幫助刪除文件開頭和結尾的多余空格。 您可能還想用下划線字符替換空格。 如果文件名不包含空格,Unix shell腳本通常會更好地工作:
for file in *
do
new_file=$(tr -s " "<<<"$file")
mv "$file" "$new_file"
done
tr -s " "
使用tr
命令從文件名中擠出空格。 這也壓縮了Mac OS X上的開始和結束空間。 這不會刪除制表符或NL(盡管可以將它們添加到字符串中)。
for file in *
中的for file in *
確實將文件名正確分配給$file
。 <<<
是一種Bashism,允許您將字符串重定向為STDIN。 這很好,因為tr
僅與STDIN一起使用。 $(...)
告訴Bash獲取該命令的輸出並將其內插到命令行中。
這是一個相當簡單的腳本,可能會阻塞其他文件名。 我建議您這樣嘗試:
for file in *
do
new_file=$(tr -s " "<<<"$file")
echo "mv '$file' '$new_file' >> output.txt
done
然后,您可以檢查output.txt
以驗證mv
命令是否可以運行。 驗證output.txt
,可以將其用作bash腳本:
$ bash output.txt
然后,它將運行您保存在output.txt中的mv
命令。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.