How can I convert tabs to spaces in every file of a directory?

后端 未结 19 1311
既然无缘
既然无缘 2020-12-02 03:48

How can I convert tabs to spaces in every file of a directory (possibly recursively)?

Also, is there a way of setting the number of spaces per tab?

19条回答
  •  星月不相逢
    2020-12-02 04:05

    Collecting the best comments from Gene's answer, the best solution by far, is by using sponge from moreutils.

    sudo apt-get install moreutils
    # The complete one-liner:
    find ./ -iname '*.java' -type f -exec bash -c 'expand -t 4 "$0" | sponge "$0"' {} \;
    

    Explanation:

    • ./ is recursively searching from current directory
    • -iname is a case insensitive match (for both *.java and *.JAVA likes)
    • type -f finds only regular files (no directories, binaries or symlinks)
    • -exec bash -c execute following commands in a subshell for each file name, {}
    • expand -t 4 expands all TABs to 4 spaces
    • sponge soak up standard input (from expand) and write to a file (the same one)*.

    NOTE: * A simple file redirection (> "$0") won't work here because it would overwrite the file too soon.

    Advantage: All original file permissions are retained and no intermediate tmp files are used.

提交回复
热议问题