2016-01-11 1 views
0

Ma chaîne est de ce format.Comment obtenir une partie du premier mot d'une chaîne de plusieurs mots en utilisant ksh

/abc/def/ghi.klm_nop.out abc def /abc/mno xxx xxx 

Ou

/abc/def/ghi.out abc def /abc/mno xxx xxx 

Ou

./ghi.klm_nop.out abc def /abc/mno xxx xxx 

Ou

./ghi.klm_nop.out abc def /abc/mno xxx xxx 

Je veux extraire uniquement

ghi.klm_nop.out 

ou ghi.out

Quel est mon meilleur pari à l'aide ksh.

J'essaie quelques choses comme

str='/abc/def/ghi.klm_nop.out abc def /abc/mno xxx xxx ' 
echo ${str##/*/} 

Mais cela ne fonctionne pas quand où est/dans les mots après. Donc, je veux d'abord obtenir le premier mot et ensuite faire quelque chose comme ci-dessus.

Répondre

0

J'utiliser read dans une boucle while pour obtenir le premier mot, puis basename à dépouiller le chemin:

while read -r path rest; do 
    file=$(basename "$path") 
    echo "$file" 
done <<END 
/abc/def/ghi.klm_nop.out abc def /abc/mno xxx xxx 
/abc/def/ghi.out abc def /abc/mno xxx xxx 
./ghi.klm_nop.out abc def /abc/mno xxx xxx 
./ghi.klm_nop.out abc def /abc/mno xxx xxx 
END 
ghi.klm_nop.out 
ghi.out 
ghi.klm_nop.out 
ghi.klm_nop.out 
0

La solution la plus proche de ce que vous avez fait (et peut-être le plus rapide) , est

echo "Internal" 
for str in "/abc/def/ghi.klm_nop.out abc def /abc/mno xxx xxx" \ 
     "/abc/def/ghi.out abc def /abc/mno xxx xxx " \ 
     "./ghi.klm_nop.out abc def /abc/mno xxx xxx " \ 
     "./ghi.klm_nop.out abc def /abc/mno xxx xxx "; do 
    tmp=${str%% *} 
    echo "${tmp##*/}" 
done 

avec beaucoup de patience, vous pouvez faire beaucoup avec sed:

echo "Sed" 
for str in "/abc/def/ghi.klm_nop.out abc def /abc/mno xxx xxx" \ 
     "/abc/def/ghi.out abc def /abc/mno xxx xxx " \ 
     "./ghi.klm_nop.out abc def /abc/mno xxx xxx " \ 
     "./ghi.klm_nop.out abc def /abc/mno xxx xxx "; do 
    echo "${str}" | sed -e 's/ .*//' -e 's#.*/##' 
done 

Et quand vous êtes prêt l'apprendre awk le mélange suivant est une option:

echo "Awk" 
for str in "/abc/def/ghi.klm_nop.out abc def /abc/mno xxx xxx" \ 
     "/abc/def/ghi.out abc def /abc/mno xxx xxx " \ 
     "./ghi.klm_nop.out abc def /abc/mno xxx xxx " \ 
     "./ghi.klm_nop.out abc def /abc/mno xxx xxx "; do 
    echo "${str%% *}"| awk -F"/" '{print $NF}' 
done