Sed and brackets
Hi!
I have a large (TeX) file in which there are lots of nested commands such as \cmd1{...}, for instance. I would like to change these to a new command \cmd2(...). Is there a way for sed to replace \cmd1{*} with \cmd2(*) * so that it replaces the correct brackets? Example: \cmd1{\somecommand{(x)}\cmd1{y}} -> \cmd2(\somecommand{(x)}\cmd2(y)) |
Hi there!
The best way for someone to help with this problem, is to show a real snippet (a real sample) of the data you're trying to operate on with sed. That way we know exactly what needs to be done, i.e. are those back-slashes actually in the data, what other troublesome characters might be in the data that will mess up one sed command making the sed command need to be written specifically to avoid this. So, show us the sed command you're currently using, and a little chunk of the real data going in, and what it should look like after it's altered, and we'll see what's what. Cheers! |
OK, here's a real snippit. The backslashes are really part of the commands themselves.
Original file: Code:
\ed{\vec{f}(x)}\ed{y^{2}} Code:
\D(\vec{f}(x))\D(y^{2}) |
Here's something to try:
Code:
sed 's/\\ed{\\vec{f}(x)}\\ed{y^{2}}/\\D(\\vec{f}(x))\\D(y^{2})/' file It appears to work (works for me!), but it will only work on precisely the string you gave; if there are other instances inside the file that you need to change too, but they are slightly different, you'll need to alter the regex. Good luck; let us know if this does the job or if it needs further refinement, or you want a new idea. |
s/\(\\ed\){\(\\vec{f}(x)\)}\\ed{\(y^{2}\)}/\\D(\1)(\2)\D(\3)/
The important bit are the \(STRING\) sections which becomes \1, \2, \3, etc. in the replacement string. I also strongly suggest putting the sed command in a separate script and invoking it with -f, that way you can avoid mysterious problems with the shell trying to use parts of your sed command for its own nefarious purposes. |
As GrapefruiTgirl said, the sed command will only work on that particular snippet you provided. If you want something more generic, you've got more work to do.
The problem is with the nested nature of the curly braces. A static regular expression will not be able to intelligently decide which closing curly brace to change. Essentially, your solution will need a rudimentary parser--something with a basic ability to keep a running tally on curly braces: +1 for each '{' and -1 for each '}' I'm no sed expert, but I think what you need to do would be best accomplished in a traditional scripting language rather than a one- or two-line sed substitution: Perl, Python, etc. (possibly awk, but I've never messed with awk much) |
Are we not overlooking the obvious, could just be me, but isn't this just:
Code:
sed 's/ed/D/' file |
Thanks for all your suggestions. I think I'll try out Python, because I do need a more general substitution.
|
Quote:
:) |
Thanks Ggirl ... missed that completely
|
All times are GMT -5. The time now is 11:42 AM. |