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

后端 未结 19 1290
既然无缘
既然无缘 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:09

    You can use the generally available pr command (man page here). For example, to convert tabs to four spaces, do this:

    pr -t -e=4 file > file.expanded
    
    • -t suppresses headers
    • -e=num expands tabs to num spaces

    To convert all files in a directory tree recursively, while skipping binary files:

    #!/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
    

    The logic for skipping binary files is from this post.

    NOTE:

    1. Doing this could be dangerous in a git or svn repo
    2. This is not the right solution if you have code files that have tabs embedded in string literals

提交回复
热议问题