简体   繁体   English

grep 在 shell 脚本中使用 sed 命令的文件夹

[英]grep the folder using sed command in shell script

I am trying to grep the folder name from full tar file.我正在尝试 grep 来自完整 tar 文件的文件夹名称。 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我想 grep shell 脚本中的文件夹名称( TEST-5.3.0.0-build1

So i tried below command for grep所以我尝试了以下命令 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:但我得到低于 output:

$ echo $package_folder

TEST-5.3.0.0-build1.x86 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我需要文件夹名称为 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.在您的命令中,您不匹配_x等。 [0-9]*[az]*[0-9]*仅匹配零个或多个数字、零个或多个(小写)字母的序列,并且零个或多个数字。 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:或者,如果x86_64也是一个常量,则只需使用字符串操作:

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:您可以在此字符串的替换部分中使用uname -m

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

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

TEST-5.3.0.0-build1

Using sed使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM