2

How do I write a sed script the rearranges/refactors a string of characters of a file?

The contents of my file are:

    for(int i=0; i<old(a, 10); i++)
    {
      sum += old(c*c, i*a)
    }

And I want the modified contents to look like:

    for(int i=0; i<new(10,0,a); i++)
    {
      sum += new(i*a, c*c)
    }
  • 1
    Does the new() function take a variable number of arguments? – RobertL Nov 2 '15 at 3:20
  • yes, is new(10,0,a) a typo? is it supposed to be new(10, a)? – cas Nov 2 '15 at 8:32
  • No, I actually wanted to know how to insert a 0 in between the 10 and a – bbycakes3 Nov 2 '15 at 20:57
2

The following works with GNU sed - it makes use of the \< and \> word-boundary markers to make sure it only changes old to new when it is a "word" by itself and not just embedded as part of a word like cold.

$ sed -e 's/\<old\>/new/g' foo.c 
    for(int i=0; i<new(a, 10); i++)
    {
      sum += new(c*c, i*a)
    }

Use GNU sed's -i option if you want it to change the file in-place rather than print to stdout.

WARNING: This sed script will change ALL occurences of /\<old\>/ in the source file. This may be much more than you want to change.

  • i didn't notice that you wanted the arg order swapped too. Keith Cascio's version does that. – cas Nov 2 '15 at 7:42
2

gnu sed:

/bin/sed -ire \
 's!\<old\(([^)]+), *([^) ][^)]*)\)!new(\2, \1)!g' \
 *.c </dev/null

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.