如何将制表符转换为一个目录的每个文件中的空格(可能递归)?
此外,是否有一种方法来设置每个制表符的空格数?
如何将制表符转换为一个目录的每个文件中的空格(可能递归)?
此外,是否有一种方法来设置每个制表符的空格数?
当前回答
将目录下的所有Java文件递归转换为4个空格而不是制表符:
find . -type f -name *.java -exec bash -c 'expand -t 4 {} > /tmp/stuff;mv /tmp/stuff {}' \;
其他回答
我的建议是使用:
find . -name '*.lua' -exec ex '+%s/\t/ /g' -cwq {} \;
评论:
Use in place editing. Keep backups in a VCS. No need to produce *.orig files. It's good practice to diff the result against your last commit to make sure this worked as expected, in any case. sed is a stream editor. Use ex for in place editing. This avoids creating extra temp files and spawning shells for each replacement as in the top answer. WARNING: This messes with all tabs, not only those used for indentation. Also it does not do context aware replacement of tabs. This was sufficient for my use case. But might not be acceptable for you. EDIT: An earlier version of this answer used find|xargs instead of find -exec. As pointed out by @gniourf-gniourf this leads to problems with spaces, quotes and control chars in file names cf. Wheeler.
尝试命令行工具expand。
expand -i -t 4 input | sponge output
在哪里
-i用于只展开每行的前导制表符; -t 4表示每个制表符将转换为4个空格字符(默认为8个)。 Sponge来自moreutils包,避免清除输入文件。在macOS上,moreutils包可以通过Homebrew (brew install moreutils)或MacPorts (sudo port install moreutils)获得。
最后,在使用Homebrew (brew install coreutils)或MacPorts (sudo port install coreutils)安装coreutils之后,可以在macOS上使用gexpand。
没有人提到rpl?使用rpl可以替换任何字符串。 要将制表符转换为空格,
rpl -R -e "\t" " " .
非常简单。
您可以使用通常可用的pr命令(此处的手册页)。例如,要将制表符转换为四个空格,可以这样做:
pr -t -e=4 file > file.expanded
-t抑制头文件 -e=num将制表符扩展为num个空格
递归转换目录树中的所有文件,跳过二进制文件:
#!/bin/bash
num=4
shopt -s globstar nullglob
for f in **/*; do
[[ -f "$f" ]] || continue # skip if not a regular file
! grep -qI "$f" && continue # skip binary files
pr -t -e=$num "$f" > "$f.expanded.$$" && mv "$f.expanded.$$" "$f"
done
跳过二进制文件的逻辑来自这篇文章。
注意:
在git或svn repo中这样做可能是危险的 如果您的代码文件在字符串字面值中嵌入了空白制表符,那么这不是正确的解决方案
警告:这会破坏你的回购。 这将破坏二进制文件,包括那些在svn, .git!使用前请阅读评论!
找到。-iname '*.java' -type f -exec sed -i。/\t/ /g' {} +
原始文件保存为[filename]. trans。
将'*.java'替换为您正在寻找的文件类型的文件结尾。这样可以防止二进制文件的意外损坏。
缺点:
将替换文件中的所有制表符。 如果在这个目录中有一个5GB的SQL转储,将花费很长时间。