tags:

views:

30

answers:

4

10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv

how can i get string between every , and _

such as aaa bbb

A: 

Heres an example

echo "10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv" | grep -o ",[^_]*_"

well, above command will include the ',' and '_' in the output To exclude this you may use

echo "10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv" | pcregrep -o "(?<=,).*?(?=_)"

The regex (?<=,).*?(?=_) passed to the pcregrep plays the important role using 'lookbehind' and 'lookahead' technique of regex which is supported by 'pcregrep'

Gopi
A: 
$ s="10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv"
$ echo $s|tr "_" "\n"|sed -n '/,/s/.*,//p'
aaa
bbb
ghostdog74
A: 

If what you're asking for is a pure Bash-solution, i.e. you do not want to call external programs, you could try something like this:

str=10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv

while [[ "$str" =~ "," ]]; do
    str=${str#*,}
    echo ${str%%_*}
done

Output is:

aaa
bbb

The while loop executes as long as there is at least one remaining comma in the string. Then the first line removes all characters from the left side of the string up to and including the first comma, and the second line prints the string excluding everything from the first underscore to the end of the string.

Note that the original string ($str) is modified.

Terje Mikal
+1  A: 

Pure Bash:

string="10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv"

IFS=','                        # separator for splitting
array=( ${string#*,} )         # split string after the first comma
array=( ${array[@]%%_*} )      # delete trailing '_*' for each element

echo -e "${array[@]}"          # gives 'aaa bbb'
fgm
Neat :) More elegant than my solution, so you deserve +1.
Terje Mikal