如何将制表符转换为一个目录的每个文件中的空格(可能递归)?

此外,是否有一种方法来设置每个制表符的空格数?


当前回答

使用反斜杠转义sed。

在linux上:

将所有*.txt文件中的所有制表符替换为1个连字符: Sed -i $'s/\t/-/g' *.txt 将所有*.txt文件中的所有制表符替换为1个空格: Sed -i $'s/\t/ /g' *.txt 将所有*.txt文件中的所有制表符替换为4个空格: Sed -i $'s/\t/ /g' *.txt

在mac电脑上:

将所有*.txt文件中的所有制表符替换为4个空格: Sed -i " $'s/\t/ /g' *.txt

其他回答

尝试命令行工具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。

你可以使用vim:

find -type f \( -name '*.css' -o -name '*.html' -o -name '*.js' -o -name '*.php' \) -execdir vim -c retab -c wq {} \;

正如Carpetsmoker所说,它将根据你的vim设置重新标签。文件中的modeline(如果有的话)。此外,它不仅将替换行首的制表符。这通常不是你想要的。例如,你可能有文字,包含制表符。

没有人提到rpl?使用rpl可以替换任何字符串。 要将制表符转换为空格,

rpl -R -e "\t" "    "  .

非常简单。

我的建议是使用:

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.

将目录下的所有Java文件递归转换为4个空格而不是制表符:

find . -type f -name *.java -exec bash -c 'expand -t 4 {} > /tmp/stuff;mv /tmp/stuff {}' \;