I'm porting a script from bash to the busybox shell, ash - how can I check what file extension a file has (and strip that extension to get a generate a directory name) ?
The bash code fragment looks like this:
if [[ "$filename" =~ '\\.tar\\.gz' ]]; then tar -xzf "$filename" dirname="${filename::${#filename}-7}" elif [[ "$filename" =~ '\\.tar\\.bz2' ]]; then tar -xjf "$filename" dirname="${filename::${#filename}-8}" elif [[ "$filename" =~ '\\.tar\\.xz' ]]; then xzcat "$filename" | tar -x dirname="${filename::${#filename}-7}" else echo "Unknown extension for file: ${filename}" >&2 exit 1
On running the script it contains I get output showing that the code to check the extension is not recognised:
Unknown extension for file: zlib-1.2.11.tar.gz
Use case
. Use basename
to remove the extension (which I find cleaner then ${var::}
expansion anyway).
case "$filename" in
*.tar.gz)
tar something
dirname=$(basename "$filename" .tar.gz)
;;
*.tar.bz2)
tar something
dirname=$(basename "$filename" .tar.gz2)
;;
# and so on
esac
Use the expr
command for regular expression matching, and the %
operator to strip a known suffix. expr
implicitly anchors all regular expressions to the beginning of the string, so you'll need to start each one with .*
to match a suffix. expr
also writes the number of characters matched to standard output, but you probably don't care to see that.
if expr "$filename" : '.*\.tar\.gz' > /dev/null; then
tar -xzf "$filename"
dirname="${filename%.tar.gz}"
elif expr "$filename" : '.*\.tar\.bz2' > /dev/null; then
tar -xjf "$filename"
dirname="${filename%.tar.gz}"
elif expr "$filename" : '.*\.tar\.xz' > /dev/null; then
xzcat "$filename" | tar -x
dirname="${filename%.tar.zx}"
else
echo "Unknown extension for file: ${filename}" >&2
exit 1
fi
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.