Feed on

i’ve just discovered sed.  this thing is wonderful; it’s like an in-line perl on the command-line.  now, it looks like i can use the shell to do things that even a perl program would be overkill for.
for instance, i’ve got these files:

[ldavid@subtilis data]$ ls
ECprot119.phy   ECprot1519.phy  ECprot19.phy    ECprot2519.phy
ECprot1219.phy  ECprot1619.phy  ECprot2019.phy  ECprot3119.phy
ECprot1319.phy  ECprot1819.phy  ECprot219.phy   ECprot519.phy

i want to strip the alphabetical characters from each filename (so that i can number my directories later).  i could use perl, or i could …

[ldavid@subtilis data]$ ls * | sed ‘s/ECprot\([0-9]*\)\.phy/\1/’

note that there are some small things to note about this sed command if you’re coming from a perl background.  first, you need to escape out the parentheses for matching.  second, sed doesn’t seem to know about “\d”; you instead have to just write “[0-9].” third, sed also doesn’t know about “+”; you’ll have to just settle for “*” to do multi-character matches.  fourth, you can’t print the match using “$1″ like in perl; instead, you write “\1″.

Bookmark and Share

if that was helpful ...

check out the other tips and tricks i've compiled on these pages. you might learn something else interesting!

3 Responses to “use ‘sed’ to give the shell perl-like powers”

  1. on 20 Aug 2008 at 2:59 pm Ivan Andrus

    Why not just use `perl -pe` instead of `sed`? Then you really have all the power of perl.

    ls | perl -pe ‘s/ECprot(\d+)\.phy/$1/’

    I realize that it takes 4 more characters to type, but that’s what aliases are for:

    alias psed=’perl -pe’

    In fact with your example you end up saving characters because of \d etc.

  2. on 21 Aug 2008 at 8:25 am Lawrence David

    i think i’m allergic to perl. still, that’s an entirely valid point ivan and it certainly makes more complex things like populating hashes from the CL easy to do …

  3. on 25 Aug 2008 at 8:28 pm Ivan Andrus

    Ah, I thought you wanted perl, but didn’t want to write a perl script. Personally, I’m allergic to sed and awk. All of the bad of perl and little of the good.

Did I get this wrong? Let me know!

Trackback URI | Comments RSS

More blogs about http://desk.stinkpot.org:8080/tricks.