我有一个Java项目,它有很多行,如下所示:
myMethod("some text here ..."
+ " ... more text here"
+ " ... and even more text here");我需要对此执行bash搜索:
"some text here ... ... more text here ... and even more text here";我尝试过这样的方法:
# Filtering for text between the two parenthesis
$ grep -rn "myMethod" . | awk -F\( '{print $2}' | awk -F\) '{print $1}' | sort | uniq
# replacing the `"$\n` with nothing
$ grep -rn "myMethod" . | sed -e 's/"$\n\s//g' | sort | uniq
# same
$ grep -rn "myMethod" . | sed -e ':a;N;$!ba;s/"$\n/,/g' | sort | uniq然而,这些都没有给我我想要的东西,那就是所有唯一的字符串都被传递到myMethod方法中。
那么,如何使用grep、awk和sed在bash中替换或过滤掉"$\n (引用行尾换行符)?
发布于 2019-03-05 17:32:16
试试这个(GNU grep和GNU sed,我相信您正在使用它们):
$ cat file
myMethod("some text here ..."
+ " ... more text here"
+ " ... and even more text here");
$ grep -rzn "myMethod" . | sed -rn '/myMethod/{:a;s/\)//;tb;N;ba;:b;s/\n//g;s/[^"]*$//;:c;s/^[^"]*"([^"]*)"(.*)/\2\1/;tc;p;}'
some text here ... ... more text here ... and even more text here
$ grep -rzn "myMethod" . | sed -rn '/myMethod/{:a;s/\)//;tb;N;ba;:b;s/\n//g;s/[^"]*$//;:c;s/^[^"]*"([^"]*)"(.*)/\2\1/;tc;s/^/"/;s/$/";/;p}'
"some text here ... ... more text here ... and even more text here";我相信它将适用于多个文件和多个事件。
我使用sed来读取后面的行,直到它找到关闭的),然后连接起来。
发布于 2019-03-05 16:58:16
这就是您想要做的(使用GNU来实现-z和承认\n)吗?
$ sed -z 's/"\n+ "//g' file
myMethod("some text here ... ... more text here ... and even more text here");
$ sed -z 's/"\n+ "//g' file | sed -n 's/^myMethod("\([^"]*\).*/\1/p'
some text here ... ... more text here ... and even more text here如果传递给myMethod的字符串可以包含转义的",那么您只需要告诉我们它们是如何转义的(加倍吗?反斜杠?还有别的事吗?)然后他们就很容易处理了。
发布于 2019-03-05 16:38:23
如果这对你有用的话,试试:
awk -F'"' '/^myMethod\(/,/\);$/{str = str " " $2}END{print str}' file对于您的输入,这将产生“这里的一些文本.这里有更多的文本.这里还有更多的文本”。如果需要,您可以很容易地修复前面的空间。
基本上使用范围模式:只在字符串myMethod(和函数结束之间搜索,调用);,然后抓取并连接$2。但是,如果同一行上有多个函数参数,则这将无法工作。您还可能需要考虑myMethod(之前和);之后的空白。
https://stackoverflow.com/questions/55006868
复制相似问题