在Unix中使用sed处理新行

时间:2016-10-16 04:51:02

标签: regex string bash unix sed

我正在将Testng断言转换为AssertJ我正在使用sed命令。当有新行如

的陈述时,我被绞死了

Exa 1:

assertEquals(person.getAddressLine1(),
        "This is long line, so needs to go in second line as per Formatter.........!!!!!!!"); 

Exa 2:

assertEquals(person.getAddressLine1(),
             "This is very long line, so needs to break down in multiple" +
                     "This is very long line, so needs to break down in multiple" +
                     "This is very long line, so needs to break down in multiple");

我当前的解决方案:这对于单行断言非常适合。

sed -i 's/assertEquals([[:blank:]]*\(.\+\),[[:blank:]]*\(["].\+["]\+\))[[:blank:]]*;/Assertions.assertThat(\1).isEqualTo(\2);/g'

注意:我知道,我可以在编辑器Formatterr中更改行的最大长度,但不知何故我无法更改它因为我需要做 Ctrl 再次+ Shift + F ,这对我来说是不可能的。

更新:两个示例的预期输出如下所示。

Exa 1:

Assertions.assertThat(person.getAddressLine1()).isEqualTo("This is long line, so needs to go in second line as per Formatter.........!!!!!!!");

Exa 2:

Assertions.assertThat(person.getAddressLine1()).isEqualTo("This is very long line, so needs to break down in multiple" +
        "This is very long line, so needs to break down in multiple" +
        "This is very long line, so needs to break down in multiple");

4 个答案:

答案 0 :(得分:0)

sed可能会这样做,但由于存在换行符,命令会更复杂。这是一个更简单的perl命令,使用slurp模式执行相同的操作:

perl -00 -pe 's/\bassertEquals\(\s*([^,]+),\s*([^)]+)\)\s*;/Assertions.assertThat($1).isEqualTo($2);/' file

RegEx Demo

使用sed即可:

sed -i -E ':a;N;s/\n[ \t]*//g;s/;/;\n/;s/assertEquals\([[:blank:]]*([^,]+),[[:blank:]]*([^)]+)\)[[:blank:]]*;/Assertions.assertThat(\1).isEqualTo(\2);/;ba' file

答案 1 :(得分:0)

感谢各位的支持,我终于可以根据我的要求使用sed了。

sed -i ':a;N;$!ba;s/[[:blank:]]*assertEquals(\([^;]\+\),\(\n[[:blank:]]*\([^;]\+\(\n\)*\)\))[[:blank:]]*;/    Assertions.assertThat(\1).isEqualTo(\2);/g' '{}' \;

答案 2 :(得分:0)

assertEquals的第一个参数完全在第一行并且不包含逗号时,这是对你想要的函数的简单近似:

sed -i 's/assertEquals(\s*\([^,]\+\),/Assertions.assertThat(\1).isEqualTo(/g'

答案 3 :(得分:0)

如果您可以访问awk,也可以

<强>脚本

awk '$0 ~ /assertEquals\(person.getAddressLine1\(\),/{
printf "Assertions.assertThat(person.getAddressLine1()).isEqualTo(";
getline;
gsub(/^[[:blank:]]*"/,"\"")}1' filename

示例输出

Assertions.assertThat(person.getAddressLine1()).isEqualTo("This is very long line, so needs to break down in multiple" +
        "This is very long line, so needs to break down in multiple" +
        "This is very long line, so needs to break down in multiple");