A sed example (with a rev!)

Dec 14th, 2005No Comments

Since I haven’t posted a lot newsworthy lately, how about a little example with sed?

I had a shell script that was spitting out some numbers into a file. I thought, “Hey, it would be nice if I added commas in the right place.” I could have rewritten my shell script in Python or Perl, but the rest of the stuff was easier to do in a shell script. Anyway, this problem might seem trivial, but it’s not. I knew a regular expression would have be created but, after a few googles also brought up that I needed reverse the string, apply the regex, and reverse the string again.

With all that, this is what I came up with:

[mikeh@gideon]>echo 1000000|rev|sed -e "s/\([0-9][0-9][0-9]\)/\1,/g"|rev
1,000,000

The \1 came from Bruce Barnett’s wonderful sed tutorial. The use of rev came from a dusty corner of my brain that something like that existed on a Unix shell.

Leave a Reply

You must be logged in to post a comment.