-   Linux - Newbie (
-   -   sed syntax (

mreff555 08-02-2012 07:40 AM

sed syntax
I found an old Oreilly book on sed/awk and was reading about it. It's syntax seems to deviate from what works present day.

The book states that something like this:


sed -e '/:/s/3/4/g' <./thing>./thing2
would go through every line but only change 3 to 4 on the first line which contains a colon.

It also states that putting a g in front:


sed -e 'g/:/s/3/4/g' <./thing>./thing2
should make it global. For me it seems to be global by default. the second sed syntax gives me an error.

I believe this book refers to the original unix sed, where I am using gnu sed. Is this someone that was changed in gnu sed or am I doing something wrong?

David the H. 08-02-2012 08:10 AM

Let's break it down one step at a time.

/:/ -- This address matches every line that has a colon in it, not just the first.
If you don't supply an address, it defaults to every line of the input. If you supply two (add1,add2), then it matches every set of lines starting and ending with those addresses.

s/3/4/ -- This substitution command, without modifers, replaces the first 3 on the line matched with a 4.

g -- (only at the end of s///g) This modifies the substitution command to replace all 3's on the line with 4's. It's not file global, it's line global.

So the command 'sed /:/ s/3/4/g' changes all 3's to 4's on lines that contain colons.

The first 'g' on your line is where the error lies. 'g' is not a stand-alone command in sed. It's only valid [in the above sense] in ed or vi/vim, where it does mean "global", i.e. apply it to all lines. In sed you simply don't supply any addresses, as I mentioned.

Edit: Correction... 'g' is a valid command, but it doesn't mean global. In sed, it copies values from the hold space back to the pattern space, and is generally used when creating multi-line commands. The grymoire tutorial goes into this stuff in more detail:

David the H. 08-02-2012 08:34 AM

To clarify a bit more, ed and vi are full text editors with random-access ability, and you need to be able to clearly tell all commands where to apply their modifications. Therefore the 'g' is used to apply them globally to all lines in the file.

sed is "stream" editor. This is important, because even though it takes it's syntax from ed/vi, it's designed to work on text in only one direction. The input flows into it from first line to last line, and sed always processes them in that order. The addresses are used to match which commands are used on which lines, and a "global" modifier isn't necessary. The 'g' has thus been re-purposed to work with the hold space instead (an extra buffer space that allows you to store text for later use).

All times are GMT -5. The time now is 10:08 AM.