简体   繁体   English

如何在shell脚本中仅从字符串中剪切“ test2-test”

[英]how to cut only “test2-test” from string in shell script

how to cut word "test2-test" from var="./test3/test2-test-10.23-67.tar.gz" 如何从var =“ ./ test3 / test2-test-10.23-67.tar.gz切出单词” test2-test“

"test2-test" could be any name, How can I do this? “ test2-test”可以是任何名称,我该怎么做?

You can use substring replacement like this: 您可以像这样使用子字符串替换:

var="./test3/test2-test-10.23-67.tar.gz"
echo ${var/test2-test/}

Output: ./test3/-10.23-67.tar.gz 输出: ./test3/-10.23-67.tar.gz

Read more about manipulating strings 阅读更多有关操纵字符串的信息


Updating answer to keep only the filename in the path using string replacing and basename : 使用字符串替换和基本名称更新答案以仅将文件名保留在路径中:

basename ${var/-[0-9]*.*/}

Output: test2-test 输出: test2-test

The answer by @Carloluis is nice, but I think the question was not properly framed. @Carloluis的回答很好,但是我认为这个问题的框架不正确。

@Samresh wanted to remove the extra part from ./test3/test2-test-10.23-67.tar.gz so that only test2-test remained. @Samresh希望从./test3/test2-test-10.23-67.tar.gz删除多余的部分,以便仅保留test2-test

It can be done by following - 可以通过以下方式完成-

basename ./test3/test2-test-10.23-67.tar.gz | sed 's/-[[:digit:]].*//'

'basename' will strip the path out, so only the filename (test2-test) remains. 'basename'将删除路径,因此仅保留文件名(test2-test)。 Next, sed can match a regex. 接下来,sed可以匹配正则表达式。 So we match the version and file extension and replace it with empty string. 因此,我们匹配版本和文件扩展名,并将其替换为空字符串。

This works for bash 4.2.46. 这适用于bash 4.2.46。

The answer by @Avi is nice, but a little slow. @Avi的答案很好,但是有点慢。 Pure bash: 纯重击:

#!/bin/bash

var="./test3/test2-test-10.23-67.tar.gz"
var=${var##*/}
var=${var%%-[0-9]*}
echo $var

100 times faster with 10000 iterations 10000次迭代速度提高100倍

bash   <  sed+basename (no builtin command)
129 ms < 13006 ms

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

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