Guilherme
Guilherme

Reputation: 21

shell how to cut out part of the string()

I have some strings... some of them have more characters other less.. here some examples.

ABC_DEF_GHI_JKL_${COD}_${DATE}
ABC_DEF_${COD}_${DATE}
ABC_${COD}_${DATE}

I have to do a function where I have to cut out the ${COD} and one _. so the new strings became

ABC_DEF_GHI_JKL_${DATE}
ABC_DEF_${DATE}
ABC_${DATE}

where the ${COD} is a number... between 1 and 300. But in the string sometimes have numbers in the middle before the ${COD}. The only sure part is that the end of them is _${COD}_${DATE} does anyone have an idea how to do it?

Upvotes: 0

Views: 447

Answers (3)

maxime.bochon
maxime.bochon

Reputation: 611

Here is a core Unix tools version:

in=AAA_BBB_123_654_20151207             # input string
n=`echo $in | grep -o _ | wc -l`        # index of field to remove     (here: 4)
nm1=`expr $n - 1`                       # index before field to remove (here: 3)
np1=`expr $n + 1`                       # index after field to remove  (here: 5)
out=`echo $in | cut -d_ -f-$nm1,$np1-`  # remove n-th field from string

Result:

echo $out
AAA_BBB_123_20151207

Upvotes: 0

chepner
chepner

Reputation: 531055

In POSIX shell, you can use

date=${str##*_}
tmp=${str%_$date}
cod=${tmp##*_}
str=${tmp%_$cod}_${date}

In bash (or another shell supporting similar array syntax), you can use

IFS=_ read -a parts <<< "$str"
cod=${parts[${#parts[@]}-2]}
# Or in bash 4.3, cod=${parts[-2]}
str=${str/_$cod_/_/}

Upvotes: 1

toddlermenot
toddlermenot

Reputation: 1618

Here is a sed version:

sed -n 's/\(.*\)_\(.*\)_\(.*\)$/\1_\3/p' filename

Greedily match the suffix and remove the unwanted part(\2) out in the replacement

Upvotes: 0

Related Questions