Siva
Siva

Reputation: 23

need to parse between second underscore and first hyphen of the text using sed

I have an rpm file, e.g. abc_defg_hijd-3.29.0-2_el6_11h.txt.

I need to parse the words between the 2nd underscore _ and first hyphen - of the above text, so the required output will be hijd.

I was able to parse the above with sed for the above, but it worked only for the above example and I have filenames which differ a little, hence I would like to explicitly parse between the second underscore and first hyphen.

Upvotes: 2

Views: 4910

Answers (5)

Endoro
Endoro

Reputation: 37589

windows batch:

for /f "tokens=3delims=_-" %%i in ("abc_defg_hijd-3.29.0-2_el6_11h.txt") do echo %%i
hijd

Upvotes: 0

Adrian Frühwirth
Adrian Frühwirth

Reputation: 45686

$ foo='abc_defg_hijd-3.29.0-2_el6_11h.txt'
$ bar=${foo%%-*}                # remove everything after the first -
$ bar=${bar#*_}; bar=${bar#*_}  # remove everything before the second _
$ echo "${bar}"
hijd

Upvotes: 3

Kent
Kent

Reputation: 195239

grep was born to extract:

grep -oP '[^_-]*_\K[^_-]*(?=-)'

example

kent$  echo 'abc_defg_hijd-3.29.0-2_el6_11h.txt'|grep -oP '[^_-]*_\K[^_-]*(?=-)'
hijd

awk is nuclear bomb for text processing,but it can kill a fly for sure:

awk -F- 'split($1,a,"_")&&$0=a[3]'

or shorter(gawk):

awk -v FPAT="[^-_]*" '$0=$3'

example

kent$  echo 'abc_defg_hijd-3.29.0-2_el6_11h.txt'|awk -F- 'split($1,a,"_")&&$0=a[3]'  
hijd


kent$  echo 'abc_defg_hijd-3.29.0-2_el6_11h.txt'|awk -v FPAT="[^-_]*" '$0=$3'
hijd

Upvotes: 2

iruvar
iruvar

Reputation: 23394

with GNU sed

echo 'abc_defg_hijd-3.29.0-2_el6_11h.txt' | 
sed 's/\([^_]\+_\)\{2\}\([^-]\+\)-.*/\2/g'
hijd

Upvotes: 0

anubhava
anubhava

Reputation: 786091

Use this sed command (on Mac):

sed -E 's/^[^_]*_[^_]*_([^-]*)-.*$/\1/'

OR (on Linux):

sed -r 's/^[^_]*_[^_]*_([^-]*)-.*$/\1/'

Using awk:

awk -F '_' '{sub(/-.*$/, "", $3); print $3}'

Upvotes: 3

Related Questions