TweetFollow Us on Twitter

Not CurSED, BlesSED!

Volume Number: 22 (2006)
Issue Number: 2
Column Tag: Programming

Mac In The Shell

Not CurSED, BlesSED!

by Edward Marczak

But sometimes, the keys to sed can be disguised.

This month, we're going to follow up on sed, the powerhouse non-interactive editor, introduced in part 1 in December's issue. Hopefully the holidays of that month didn't take you away from really digging in and putting the lessons into practice. If you did take it all in, you've probably found several uses for it already. This month, we'll visit more sed mnemonics and add a few new tricks.

Bob's Yer Uncle

A few reminders about sed regarding redirection and piping. In part 1, we worked on a single file, viewing the results on screen. There are some things I need to clear up before continuing.

Naturally, you can redirect the output from sed to a file. What I didn't mention last month is a tendency that many first-time sed users need to stay away from. Namely, redirecting to the same file that you're working on. Sure, you've tested your script and you're 100% confident that it's going to Do The Right Thing. So, you do this:

sed -f myscript.sed long_text_file.txt > long_text_file.txt

Seems perfectly natural, right? We'll, sorry, you can't do that. You can't redirect to the same file you're altering. This is not an issue with sed, but just the way the shell works. The shell will truncate the destination file before it executes your command. So, while it seems like it might work, it doesn't. You need to write to a temporary file first, and then overwrite the original if you desire to do so. The desired effect is achieved like this:

$ sed -f myscript.sed long_text_file.txt > tmp_file.txt
$ mv -f tmp_file.txt long_text_file.txt

Also, it may not have been clear from the introductory article that sed is happy to work 'on-the-fly' by accepting and pumping out data via a pipe. To get a count of directories in a certain folder, for example, you could do this:

ls -lRF /Users/marczak/Documents | grep "^/" | sed s/:/'\/'/ | sed s/\ /'\\ '/g | wc -l

Pipe-to-pipe-to-pipe-to-pipe! However, a sed master will never use two sed statements where one would do. This can also be written as:

ls -lRF /Users/marczak/Documents | grep "^/" | sed -e s/:/'\/'/ -e s/\ /'\\ '/g | wc -l

In short, pipe away, redirect carefully, and Bob's yer uncle!

Do it Better

While the information in part 1 of this article is more than enough for very powerful manipulations, you still may run into some limitations. That's why part 1 was the introduction: there's still more!

First, I mentioned that I would give the solution the 'swapping Bill and Michael' problem. The answer, of course, is, "it depends." You really have to be familiar with your source material. For now, I'll show the easy, yet most brute-force way of handling our scenario. Remember, the source text is this:

    Bill and Michael went to the store. Bill needed to buy some butter, eggs and flour. He and Michael were in a hurry to bake a cake for their parent's Anniversary. Once they got home, Bill and Michael realized that they forgot cake icing.

Just like writing any code, you can swap using a temporary variable (sorry - sed doesn't quite have anything like a bitwise swap!). So, here you go:

sed -e 's/Bill/David/g' -e 's/Michael/Bill/g' -e 's/David/Michael/g' short_story.txt

In our case, we probably really only want the fully qualified "Bill and Michael", so we can actually do just that:

sed 's/Bill and Michael/Michael and Bill/g' short_story.txt

However, you may realize, that this does not take into account line endings. What if our phrase crosses a newline boundary? Ah! That's where multi-line commands come in.

Multi-line commands give sed the ability to look at more than one line in the pattern space. This gives the sed script-crafter the ability to inject a little logic into the flow. Since our story does not split "Bill and Michael" anywhere, let's look at something that does: "buy some...". If we wanted to change all occurrences of "buy some" to "purchase some", even if it spans lines, we need to coax sed into doing so. Again, the brute-force way is simply this:

/buy/ {
N
s/buy *\n*some/purchase some/
}

Here, we look for the address "buy" and when found, run a multi-line next ("N") command. This command reads the next line of input and appends it to the current pattern space - still 'separated' by a new line. Like I said, brute-force, and doesn't really scale well. Also, this has the potential of outputting some really long lines. Of course, elegance is just around the corner. A script that gives us use in more general cases could look like this:

/buy/ {
N
s/ *\n/ /
s/buy some */purchase milk,\
/
}

First, we look for the address "buy", and if we find it, we pull the next line into the pattern space with "N". Then, we can ditch the new line character and replace it with a space. From there we can try to match our patterns. However, even this is a little problematic - just a drop. The example just given works just fine, but let's alter our story and script. Adding a line to the story to make it this:

    Bill and Michael went to the store. Bill needed to buy some butter, eggs and flour. He and Michael were in a hurry to bake a cake for their parent's Anniversary. Once they got home, Bill and Michael realized that they forgot cake icing. It is important that they had not forgotten anything for the special day.

And changing the script to this:

/got/ {
N
s/ *\n/ /
s/got home */returned to their abode\
/
}

...will lead to problems. The goal of this script is to change all occurrences of "got home" into "returned to their abode". Run it and see what happens. See the problem? "got" matches "forgotten" on the last line, but makes no substitutions, so the script quits without outputting that line. It's just MIA! What to do? Exempt the last line of the script. Change the "N" to "$!N" - sed recognizes "$" as the last line (not EOL like regexp).

The reality is that you'll find many, many, many examples like this. Depending on your source(s), you may only be able to make a script just so general. This goes back to the rule: test, test, test! You can't test your script enough.

Loose Fit

In addition to the main pattern space that sed matches and manipulates, there is also a hold buffer. The commands are pretty self explanatory: 'x' will eXchange the pattern space with the hold buffer. 'h' will copy the current pattern space into the hold buffer, overwriting what was being held previously. 'H' will do the same, but append to the current hold buffer. 'g' gets the contents of the hold buffer and replaces the pattern space. 'G' gets the contents of the hold buffer and appends its contents to the current pattern space.

Before I get into these commands, please remember that sed certainly is a descendent of the phrase TIMTOWTDI - There is more than one way to do it. Many times, there will be multiple solutions to the particular problem you're trying to overcome. Build up one piece at a time, test, and for goodness sake, document your solution! (Did I mention that sed scripts recognize "#" as a comment?)

So, let's say we want to print the line before and the line after our match, so we can see it in context - like grep's 'A', 'B', and 'C' flags. Here's one way to approach this:

sed -n '
'/Anniversary/' !{
# lines that do not match what we're looking for - save
x
# clear the current pattern buffer with delete
d
}
'/Anniversary/' {
# lines that match
# get the previous line from the hold buffer
x
# print it with p
p
# get the current line back from the hold buffer
x
# print that
p
# get the next line
n
# print it
p
# finally, drop this line into the hold buffer
x
}' short_story.txt

Going back to our short story, this will look for a line containing 'Anniversary', print the line before it, the line itself, and the line following. Note the use of the "-n" switch passed into sed. This switch tells sed to not print all output by default. Otherwise, you'll still see all of your input as it filters through sed. Of course, to make all of this more useful, you could drop this right into a shell script, and use $1 for the pattern - this would give you a generic script that will always perform the equivalent of "grep -C 1 pattern file.txt". Just remember: the way I broke this up over several lines is very bash specific. csh users must use the backslash to tell the interpreter that the line continues on.

Step On

Earlier, I alluded to sed as a programming language by mentioning the classic temp-variable-swap. Well, sed tends to be more full featured than most people realize. You can even implement flow-control! sed features two commands that let you control the logic of your script. 'b' branches to a label. (Reminds me of my favorite Motorola Assembly mnemonic - BRA - BRanch Always). One example, and you'll get it. This script is an alternate to the script just presented that emulates 'grep -C 1':

# find our pattern? jump!
/Anniversary/ b printit
# else hold it
h
# jump to end of script
b
:printit
# get previous line from hold buf
x
# print it
p
# get current line back
x
# print it
p
# get next line
n
# print that
p

First to note is the label. A label starts a line with a colon, and should contain seven characters or less. While most modern implementations allow a label to be any length - and is actually the POSIX spec - there are still some versions of sed that restrict a label to 7 characters max. With 'b', we just branch - make the jump. Another flow-control command is 't', or, test. Test allows us to branch conditionally. The jump only happens if the previous substitution was successful. Another example is in order. Imagine a file that lists a userclass by number, and it should be by name. Additionally, you must process the file differently for each userclass. Here's a mock script that could handle this:

/userclass/{
s/2000/executive/
t excpath
s/1500/management/
t manpath
s/1000/staff/
t stpath
# default action
=
b
:excpath
...
b
:manpath
...
b
:stpath
...
# end of script

Those examples should get you going with flow control in sed. Remember, you can certainly jump to a label ahead of your test and even get into (basic) recursion!

Harmony

There are a bunch of miscellaneous things that I'd like to point out before we wrap up our conversation about sed. Some of these fall into the "you have to know the rules before you can break them" category, so I waited to present them.

All of the examples I've given, and most that you'll see, use a forward slash ("/") as the delimiter. Amazingly, sed lets you use whatever you like. The delimiter is great if you have a very simple replacement, such as sed s/one/two/g. However, if you're replacing file paths, that could get messy. So, use an underscore, if you like: sed 's_/usr/sbin_/usr/bin_'. Easier to read, right?

The "=" (equal sign) mnemonic prints out the current line number. So, you can simply line number any text file:

sed '=' textfile.txt

Or, you can use to just find the lines that the pattern you're looking for lie in:

sed -n '/Bill/ =' story.txt

You've probably picked these two up by now, but I should make them clear. Quoting: you really only need to quote if you have metacharacters, but it's a good habit to get into. This: sed s/Bill/Mike/g is the same as this: sed 's/Bill/ Mike/g'. However, try this: sed s/.*address*\ (astring\)\(\1)$1)/ and sed is just going to cough up electrons. The second thing is the use of the "-e" switch. If you only have one command, you can forgo the "-e". If you have multiple commands, you need to add each of them to the list of editing commands with the "-e" switch.

Lastly, a note about newlines, or, EOL. Somewhat confusingly, you match a newline with the standard regexp '\n'. However, to output a newline, you use a literal newline:

sed 's/Bill/Bill\
/g' story.txt

This will drop a newline after every occurrence of 'Bill' in our sample text.

Cut 'Em Loose Bruce

...and I thought I was going to get to awk this month! Hopefully, this gives you some ideas about sed and its power. I also hope with practice, that you use this power. You really have to see sed as an editor. It just happens to be one that you don't use interactively like vi, emacs or pico. Go forth and edit non-interactively! sed is an indispensable tool for any system administrator's toolchest, and there are plenty of repetitive tasks waiting for you to automate.


Ed Marczak owns and operates Radiotope, a technology consulting company. Despite being around the technology block once or twice, he's thankful that there's always something new to look forward to. Something new at http://www.radiotope.com

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.