BashScripts.org
http://bashscripts.org/forum/

Basic sed
http://bashscripts.org/forum/viewtopic.php?f=21&t=431
Page 1 of 1

Author:  JuanManuel [ Wed Oct 10, 2007 12:41 pm ]
Post subject:  Basic sed

I'm working on a script layout to have "theming scripts", that is, to be able to change lots of things appearance with just a command =P
I came to the conclusion that I will need to learn sed, and I'm on it. But some handy help would come great now =D
The only thing that rests unchangeable to me is my Openbox theme. There is a config file called rc.xml on ~/.config/openbox with a line that simply encloses the theme name between <theme><name></name></theme>

Now, I learned that with sed I can use -i option to take the input from the same file where I write the output. I asked for help on Freenode #Bash, but got a quickly "no" and a recommendation to use portable tools, like ed instead of sed. Is that advisable?

In any case, I found some lines on a script that seems to do something similar:

Code:
CFGDIR=$HOME/.config/openbox
cat $CFGDIR/rc.xml > $CFGDIR/rc.temp
sed -e "/<theme>/{n;s/\(<name>\).*\(<\/name>\)/\1$1\2/;}" $CFGDIR/rc.temp > rc.xml


Tell you what I don't get:

- The use of the -e option in this case. I'd understood that it's used to have multiple replacements on the same sed instance.
- The {n;s part.
- Why it uses parentheses.

Thanks for your time!

Author:  jeo [ Thu Oct 11, 2007 8:53 am ]
Post subject: 

Hey Juan, I know what you mean. I'll research this if I get a chance today. There is so much that you can do with sed, and so many options :)

Author:  jsz [ Sat Jun 11, 2011 8:29 am ]
Post subject:  Re: Basic sed

Yes, sed(1) doesn't really edit files because it uses temporary ones, whereas ed(1) is an editor, not a stream editor.

The use of the -e option is not needed in this case, as the braces that just group commands.
The n command is here to « jump » to the line after the pattern <theme> was matched.

Code:
# search for the pattern «  <theme> »
/<theme>/

# read the next line
n

# only retrieve the pattern « <name> » and « </name> », then put a variable value in between

    # use the  (s)ubstitute  command
    s/

    # retrieve the pattern « <name> » from the line
    \(<name>\)

    # don't catch what's between the tags
    .*

    # retrieve the pattern « </name> » from the line
    \(<\/name>\)

    # end of the regex part
    /

    # replace the whole line by the first pattern matched ( « <name> » ), followed by the first argument
      passed to the script, then the second pattern that we matched ( « </name> » )
    \1$1\2

    # end of  s  command
    /

Page 1 of 1 All times are UTC - 6 hours
© 2000, 2002, 2005, 2007 phpBB Group • http://www.phpbb.com