soField
soField

Reputation: 2696

substring by char range

10.11.183.81,aaa_XXX150.csv,bbb_YYYY_20100807.csv

how can i get string between every , and _

such as aaa bbb

Upvotes: 0

Views: 264

Answers (4)

Fritz G. Mehner
Fritz G. Mehner

Reputation: 17198

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'

Upvotes: 1

Terje Mikal
Terje Mikal

Reputation: 947

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.

Upvotes: 0

Gopi
Gopi

Reputation: 10293

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'

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342649

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

Upvotes: 0

Related Questions