您不需要使用 IFS。只需将您的论点附在 "" 周围即可防止分词:
mv "${f}" "$(echo "${f}" | sed 's/\n//g')"
另外,您可以使用特殊的参数扩展来删除换行符:
mv "${f}" "${f//$'\n'}"
请参阅 Word Splitting 和 Parameter Expansion。
注意:只有开放变量受 IFS 影响。像 * 这样的即时 glob 模式在展开时不会拆分。
要启用 glob 递归,请启用 globstar: shopt -s globstar。然后就可以了
for f in /path/to/dir/**; do
[[ ! -d $f ]] && mv "$f" "${f//$'\n'}" ## Test lets it process files only.
done
使用find:
find -type f '/path/to/dir' -print0 | while IFS= read -rd '' f; do
mv "$f" "${f//$'\n'}"
done
与使用进程替换相同:
while IFS= read -rd ''; do
mv "$f" "${f//$'\n'}"
done < <(exec find -type f '/path/to/dir' -print0)
使用IFS=,read 禁用输入的分词。 -r 禁用解释反斜杠引号,-d '' 将分隔符设置为 0x00。它与find 一起使用,它将0x00 设置为输出分隔符,而不是-print0 的换行符(0x0A)。
也可以使用字符集:
[:alpha:] Alphabetic characters.
[:blank:] Space and TAB characters.
[:cntrl:] Control characters.
[:digit:] Numeric characters.
[:graph:] Characters that are both printable and visible.
[:lower:] Lowercase alphabetic characters.
[:print:] Printable characters (characters that are not control characters).
[:punct:] Punctuation characters (characters that are not letters, digits,
[:space:] Space characters (such as space, TAB, and formfeed, to name a few).
[:upper:] Uppercase alphabetic characters.
[:xdigit:] Characters that are hexadecimal digits.
你可能想要:
mv "$f" "${f//[[:cntrl:]]}"
或者
mv "$f" "${f//[^[:print:]]}" ## Does not only include control chars but probably some if not all extended chars as well.
你也可以加入他们:
mv "$f" "${f//[[:cntrl:]|!@#$%^&*()]}"
当然,在实际运行之前先对其进行测试:
echo mv "$f" "${f//[[:cntrl:]|!@#$%^&*()]}"