需要SED或AWK脚本来进行strlen优化(Need SED or AWK script to do strlen optimization)

编程入门 行业动态 更新时间:2024-10-26 19:27:18
需要SED或AWK脚本来进行strlen优化(Need SED or AWK script to do strlen optimization)

我只需要一点帮助,因为我很少碰到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.

更多推荐

本文发布于:2023-08-03 09:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1385359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   AWK   SED   optimization   script

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!