简体   繁体   中英

How to get part of the first word in a string of multiple words using ksh

My string is of this format.

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

Or

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

Or

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

Or

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

I want to extract out only

ghi.klm_nop.out

or ghi.out

Whats my best bet using ksh.

I am trying a few things like

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

But this does not work when where is / in the words after. So i first want to get the first word and then do something like above.

I would use read in a while loop to get the first word, then basename to strip off the path:

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

The solution closest to what you did (and perhaps fastest), is

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

With a lot patience you can do a lot with 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

And when you are willing the learn awk the next mixture is an 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM