I would like to extract only tar.gz
from the following strings.
/root/abc/xzy/file_tar_src-5.2.8.23.tar.gz
or
/root/abc/xyz/file_tar_src-5.2.tar.gz
or
/root/abc/xyz/file_tar_src-5.tar.gz
out of all these strings (and many more) I need only tar.gz
How do I extract them without concerned about the number of dots in them. I need to get the tar.gz
in a variable.
I really don't understand why you need only tar.gz
:
$ x=/root/abc/xyz/file_tar_src-5.tar.gz
$ y=${x##*[0-9].}
$ echo $y
tar.gz
Or:
$ x=/root/abc/xyz/file_tar_src-5.tar.gz
$ y=`echo $x | grep -o 'tar\.gz$'`
$ echo $y
tar.gz
It's tricky because you're not expecting the version number to be matched. We'll need more power than just plain wildcards. We can use bash's built-in =~
regex operator to get the job done.
$ filename='/root/abc/xzy/file_tar_src-5.2.8.23.tar.gz'
$ [[ $filename =~ \.([^0-9]*)$ ]]
$ ext=${BASH_REMATCH[1]}
$ echo "$ext"
tar.gz
$ f='/root/abc/xzy/file_tar_src-5.2.8.23.tar.gz'
$ [[ $f =~ [^.]+\.[^.]+$ ]] && echo ${BASH_REMATCH[0]}
tar.gz
Not sure exactly what you're looking for. Are you trying to determine if the file ends with tar.gz
?
if [[ $filename == *.tar.gz ]]
then
echo "$filename is a gzipped compressed tar archive"
else
echo "No, it's not"
fi
Are you attempting to find the suffix whether it's tar.gz
, tar.bz2
or just plain tar
?
$suffix=${file##*.tar}
if [[ "$suffix" = "$file" ]]
then
echo "Not a tar archive!"
else
suffix="tar.$suffix"
echo "Suffix is '$suffix'"
fi
Are you interested in the suffix, but if it's a tar.gz, you want to consider that the suffix:
filename='/root/abc/xzy/file_tar_src-5.2.8.23.tar.gz'
suffix=${filename##*.} #This will be gz or whatever the suffix
rest_of_file=${filename%%.$suffix} #This is '/root/abc/xzy/file_tar_src-5.2.8.23.tar'
# See if the rest of file has a tar suffix.
# If it does, prepend it to the current suffix
[[ $rest_of_file == *.tar ]] && suffix="tar.$suffix"
echo "The file suffix is '$suffix'"
Another on:
pathname="/root/abc/xzy/file_tar_src-5.2.8.23.tar.gz"
IFS='.' # field separator
declare -a part=( ${pathname} ) # split into an array
ext2="${part[*]: -2}" # use the last 2 elements
echo -e "${ext2}"
.tar.bz2
? Do you still wanttar.gz
or do you want.tar.bz2
? If you're only ever usingtar.gz
, you don't need to get the extension; you know it istar.gz
. What happens withfile.c
? Is that extension.c
orfile.c
or is it just invalid because there's only one dot in the name? Do you ever need the prefix, the non-extension? Or do you mean 'get everything except the trailingtar.gz
? Do you want the terminal dot - Jonathan Leffler 2012-04-04 01:05