简体   繁体   中英

grep the folder using sed command in shell script

I am trying to grep the folder name from full tar file. Below is the example.

example:

TEST-5.3.0.0-build1.x86_64.tar.gz

I want to grep the folder name ( TEST-5.3.0.0-build1 ) in shell script

So i tried below command for grep

$ package_folder=$(echo TEST-5.3.0.0-build1.x86_64.tar.gz | sed -e "s/.[0-9]*[a-z]*[0-9]*.tar.gz$//" | sed -e 's/\/$//')

But I am getting below output:

$ echo $package_folder

TEST-5.3.0.0-build1.x86

Could you please anyone correct me where I am doing mistake. I need folder name as TEST-5.3.0.0-build1

Thanks in Advance!!!

In your command, you do not match _ , x , etc. The [0-9]*[az]*[0-9]* only matches a sequence of zero or more digits, zero or more (lowercase) letters, and zero or more digits. It is better to use a [^.]* to match any chars other than . between two . chars. Also, literal dots must be escaped, or an unescaped . will match any single char.

You can use

sed 's/\.[^.]*\.tar\.gz$//'

Or, just use string manipulation if x86_64 is also a constant:

s='TEST-5.3.0.0-build1.x86_64.tar.gz'
s="${s/.x86_64.tar.gz/}"

See the online demo :

#!/bin/bash
s='TEST-5.3.0.0-build1.x86_64.tar.gz'

package_folder=$(sed 's/\.[^.]*\.tar\.gz$//' <<< "$s")
echo "${package_folder}"
# => TEST-5.3.0.0-build1

s="${s/.x86_64.tar.gz/}"
echo "$s"
# => TEST-5.3.0.0-build1

You can use uname -m in replacement part of this string:

s='TEST-5.3.0.0-build1.x86_64.tar.gz'
echo "${s%.$(uname -m)*}"

TEST-5.3.0.0-build1

Or using sed :

sed "s/\.$(uname -m).*//" <<< "$s"

TEST-5.3.0.0-build1

Using sed

$ package_folder=$(echo "TEST-5.3.0.0-build1.x86_64.tar.gz" | sed 's/\(.*\)\.x86.*/\1/')
$ echo "$package_folder"
TEST-5.3.0.0-build1

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