tags:

views:

42

answers:

3

I have a loop in a bash file to show me all of the files in a directory, each as its own variable. I need to take that variable (filename) and parse out only a section of it.

Example:

92378478234978ehbWHATIWANT#98712398712398723

Now, assuming "ehb" and the pound symbol never change, how can I just capture WHATIWANT into its own variable?


So far I have:

#!/bin/bash
for FILENAME in `dir -d *` ; do

done


A: 

One possibility:

for i in '92378478234978ehbWHATIWANT#98712398712398723' ; do
    j=$(echo $i | sed -e 's/^.*ehb//' -e 's/#.*$//')
    echo $j
done

produces:

WHATIWANT
paxdiablo
+6  A: 

You can use sed to edit out the parts you don't want.

want=$(echo "$FILENAME" | sed -e 's/.*ehb\(.*\)#.*/\1/')

Or you can use Bash's parameter expansion to strip out the tail and head.

want=${FILENAME%#*}; want=${want#*ehb}
ephemient
A: 

using only the bash shell, no need external tools

$ string=92378478234978ehbWHATIWANT#98712398712398723
$ echo ${string#*ehb}
WHATIWANT#98712398712398723
$ string=${string#*ehb}
$ echo ${string%#*}
WHATIWANT