Home > Software design >  grep the folder using sed command in shell script
grep the folder using sed command in shell script

Time:12-07

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!!!

CodePudding user response:

In your command, you do not match _, x, etc. The [0-9]*[a-z]*[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

CodePudding user response:

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

CodePudding user response:

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
  • Related