我只需要一点帮助,因为我很少碰到sed或awk。 我正在尝试更换
String1.append("Hello"); // regexp to find this is: \w*\.append\(".*"\)同
String1.append("Hello", 5); // note it has to figure out the length of "Hello"我需要做这个搜索并替换成千上万的文件。 和“你好可能是任何东西......包括”\ n \ n \ n“这应该是3而不是6。
s.append("\n\n\n"); ---> s.append("\n\n\n", 3);预先感谢任何帮助...我想我需要awk来做到这一点,所以我现在正在阅读有关awk基础知识的教程...
I just need a little help cause I rarely touch sed or awk. I'm trying to replace
String1.append("Hello"); // regexp to find this is: \w*\.append\(".*"\)with
String1.append("Hello", 5); // note it has to figure out the length of "Hello"And I need to do this search and replace across hundreds of thousands of files. And "Hello could be anything... including "\n\n\n" which should be 3 not 6. Example:
s.append("\n\n\n"); ---> s.append("\n\n\n", 3);Thanks in advance for any help... I'm thinking I need awk to do this so I'm reading a tutorial about the basics of awk right now...
最满意答案
既然你想在一些包含代码的文件上运行它,下面是一个完整功能的例子:
$ cat file foo() { String1.append("Hello"); if (bar) { s.append("\n\n\n"); } else { s.append("\n\\n\n\\\n"); } } $ $ cat tst.awk match($0,/[[:alnum:]_]+\.append\(".*"\)/) { split(substr($0,RSTART,RLENGTH), orig, /"/) head = substr($0,1,RSTART-1) orig[1] tail = orig[3] substr($0,RSTART+RLENGTH) tgt = orig[2] gsub(/[\\][\\]/,"X",tgt) gsub(/[\\]/,"",tgt) $0 = sprintf("%s\"%s\", %d%s", head, orig[2], length(tgt), tail) } { print } $ $ awk -f tst.awk file foo() { String1.append("Hello", 5); if (bar) { s.append("\n\n\n", 3); } else { s.append("\n\\n\n\\\n", 6); } }为了便于携带,我将原始发布的问题中的“\ w”替换为POSIX等效的“[[:alnum:] _]”。 “\ w”将使用GNU awk和一些其他工具,但不是所有的工具,也不是所有的awks。
Since you want to run this on some files containing code, here's an example of that full functionality:
$ cat file foo() { String1.append("Hello"); if (bar) { s.append("\n\n\n"); } else { s.append("\n\\n\n\\\n"); } } $ $ cat tst.awk match($0,/[[:alnum:]_]+\.append\(".*"\)/) { split(substr($0,RSTART,RLENGTH), orig, /"/) head = substr($0,1,RSTART-1) orig[1] tail = orig[3] substr($0,RSTART+RLENGTH) tgt = orig[2] gsub(/[\\][\\]/,"X",tgt) gsub(/[\\]/,"",tgt) $0 = sprintf("%s\"%s\", %d%s", head, orig[2], length(tgt), tail) } { print } $ $ awk -f tst.awk file foo() { String1.append("Hello", 5); if (bar) { s.append("\n\n\n", 3); } else { s.append("\n\\n\n\\\n", 6); } }I replaced the "\w" from the example in the original posted question with the POSIX equivalent "[[:alnum:]_]" for portability. "\w" will work with GNU awk and some other tools, but not all tools and not all awks.
更多推荐
发布评论