Comment obtenir une sous-chaîne après le dernier trait de soulignement (_) dans le script shell unix

J’ai une chaîne comme ça

this_is_test_ssortingng1_22 this_is_also_test_ssortingng12_6 

Je voulais diviser et extraire la chaîne autour du dernier trait de soulignement. C’est ce que je voulais les sorties comme ça

 this_is_test_ssortingng1 and 22 this_is_also_test_ssortingng12 and 6 

Quelqu’un peut-il m’aider à obtenir cela dans les scripts shell Unix.

Merci. Sree

Tu peux faire

 s='this_is_test_ssortingng1_22' 

Dans BASH:

 echo "${s##*_}" 22 

OU en utilisant sed:

 sed 's/^.*_\([^_]*\)$/\1/' <<< 'this_is_test_string1_22' 22 

EDIT pour sh:

 echo "$s" | sed 's/^.*_\([^_]*\)$/\1/' 

Donc, mettre des idées de anubhava et de glenn … Le script Full Shell peut être … comme par la suite. vous pouvez choisir de générer un fichier ou un affichage sur la ligne de commande …

 #!/bin/ksh #FILE=/paht/to/file.txt or you can pass argument FILE=$1 FILE=$1 counter=`wc -l $FILE |cut -d " " -f1` x=1 while [ $x -le $counter ] do REC=`sed -n ${x}p $FILE` echo " ${REC%_*} and ${REC##*_} " >> output.txt let x=$x+1 done 

Utiliser awk :

 $ awk 'BEGIN{FS=OFS="_"}{last=$NF;NF--;print $0" "last}' < this_is_test_ssortingng1_22 > this_is_also_test_ssortingng12_6 > EOF this_is_test_ssortingng1 22 this_is_also_test_ssortingng12 6