Need SED or AWK script to do strlen optimization

awk, regex, sed

Solution

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.

Problem

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...

Original source