sed命令行改变" aas = aas"进入" aas = aas"

时间:2017-04-06 17:26:22

标签: regex linux macos sed

正则表达式/ sed专家的问题: 我需要美化一些c ++代码。 代码中充斥着具有不同类型间距的赋值运算符的各种版本。 即。

a=b
a =b
a= B
a  = b
a=  b
A = B. // the correct format needed, and so must be ignored by SED

=周围应该只有一个空格。如果找到更多,则必须删除额外内容。

我需要创建一个脚本来扫描文件夹和子文件夹中的所有文件,并根据需要进行搜索和替换。

有一些变化,比如a + = b等。

我在OsX上运行但是有Linux和Windows机器可用。

非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用此sed在所有=运算符之前和之后插入单个空格:

输入文件:

cat file
a          ==b
a=b
a =b
a/=b
a *=b
a+= b
a-=   b
a= B
a%= B
a  = b
a=  b
A = B

sed命令:

sed -E 's~[[:blank:]]*([-+*/%=]?=)[[:blank:]]*~ \1 ~g' file

a == b
a = b
a = b
a /= b
a *= b
a += b
a -= b
a = B
a %= B
a = b
a = b
A = B

这是用于匹配的正则表达式(使用~作为分隔符):

  • ~[[:blank:]]*([-+*/%=]?=)[[:blank:]]*~ - 匹配0个或更多空格,后跟文字-+*/%=之前的可选=个字符。我们还在第1组
  • 中捕获此运算符

这是用于替换的模式:

  • ~ \1 ~表示在组#1
  • 中捕获的字符串之前和之后的空格

答案 1 :(得分:0)

您可能会对使用Perl

进行操作感兴趣

一个简单的file.cpp

#include <iostream>

int main(){
    int i =          3;
    i     += 3;
    i-=3;
    i   *  =    3; // not valid just for sure
    i/=3;

    int i2
    =
    3;

    if( i
       =
       = i2 ){} // not valid just for sure
}

perl -lpe '$/=undef;s/\s*([=!%\*\/+-])?\s*(=)\s*/ $1$2 /g' file.cpp

输出:

#include <iostream>

int main(){
    int i = 3;
    i += 3;
    i -= 3;
    i *= 3;
    i /= 3;

    int i2 = 3;

    if( i == i2 ){}
}