Search code examples
bashshellcut

cut the string using string as delimiter in Shell


Need to print libcom.so by stripping out 1.0.0 when it prints first line.

#!/bin/sh
data=$(sed '0,/^__VERSION__$/d' "$0")
for d in $data
do
     echo with version:
     echo $d
     echo "with no version" 
     d1="$(cut -d\.so -f1 <<< $d)"
     #Need to save it in a variable for further processing
     echo $d1
done

exit

__VERSION__
libcom.so.1.0.0
libclock.so.1.0.0
libstdc++.so.6.0.20
libxml.so.2.7.8
libmi.so.1.0.0
librt.so.6.6.5
libcsapi.so.1.0.0

error out as cut: the delimiter must be a single character, whats the best way to do this?


Solution

  • If you just want the string up until the first .so, bash will happily handle it for you:

    d1="${d%%.so*}.so"
    

    The ${d%%.so*} deletes the longest string from the right side %% of the variable d that matches .so*. This effectively removes everything starting with .so until the end of the string. We then manually re-add the .so we removed because %% removes the entire matched portion, not just the wildcard portion.

    See this guide on parameter expansion for more detail.


    Alternately, you could use sed even though it would be considerably slower:

    d1=$(sed 's/\(\.so\).*$/\1/' <<< $d)