每个文件递归地用四个空格替换每个前导标签

Ali*_*scu 4 regex sed indentation

什么是最容易实现Linux中的这个使用常用工具的方法是什么?

我看了看:

  1. sed,但是对如何计算类似的表达式中匹配的前导制表符还不了解sed -i 's/^[\t]*/<what-to-put-here?>/g myFile.c
  2. astyle,但无法弄清楚如何重新缩进和不格式化
  3. indent,与astyle一样的问题
  4. expand,但它也替换了非前导标签,并且我必须亲自处理就地替换,这很容易出错。

我只是在寻找一种快速简便的解决方案,可以将其插入 find -type f -name "*.c" -exec '<tabs-to-spaces-cmd> {}' \;

enr*_*cis 5

您应该真正使用expand它,因为它仅是为此而开发的。从其文档中

-i, --initial
   do not convert tabs after non blanks
Run Code Online (Sandbox Code Playgroud)

因此,单个文件的命令为:

expand -i -t 4 input > output
Run Code Online (Sandbox Code Playgroud)

为了与多个文件一起使用,您将需要一个技巧:

expand_f () {
  expand -i -t 4 "$1" > "$1.tmp"
  mv "$1.tmp" "$1"
}

export -f expand_f
find -type f -iname '*.c' -exec bash -c 'expand_f {}' \;
Run Code Online (Sandbox Code Playgroud)

这用于防止expand在文件仍在处理时写入文件,并避免重定向stdout find而不是重定向其中的一个expand


pot*_*ong 3

这可能对你有用(GNU sed):

sed -ri ':a;s/^( *)\t/\1    /;ta' file
Run Code Online (Sandbox Code Playgroud)