简体   繁体   English

重击-子串提取

[英]Bash - substring extraction

I have a variable "$var" of type: "YYYYMMDD_charcharchar...charchar.ext" After the first "_" there can be other one (1 or more) or none. 我有一个变量"$var" ,类型为: "YYYYMMDD_charcharchar...charchar.ext"在第一个“ _”之后可以有另一个(1个或多个),也可以没有。

I have to truncate the first part "YYYYMMDD_" and leave in a $new_var "charcharchar...charchar.ext" . 我必须截断第一部分"YYYYMMDD_"然后保留$new_var "charcharchar...charchar.ext"

I can't use "bash expansions" like ${string:position} because I'm into emulated environment (Cygwin) 我无法使用${string:position}类的“ bash扩展”,因为我进入了模拟环境(Cygwin)

thanks. 谢谢。

You tagged the question with awk, so here is an example with awk: 您用awk标记了问题,因此以下是awk的示例:

$ var="YYYYMMDD_foo_bar_blah"
$ newV=$(awk 'sub(/^[^_]*_/,"")' <<<$var) 
$ echo $newV
foo_bar_blah

This is easier done using cut : 使用cut更容易做到这一点:

var="YYYYMMDD_charcharchar...charchar.ext"

new_var=$(echo "$var" | cut -d_ -f2-)

Check output: 检查输出:

echo "$new_var"

charcharchar...charchar.ext

Just use parameter expansion: 只需使用参数扩展:

new_var=${var#*_}

The # operator removes from the expansion the shortest prefix matching *_ (which would be any characters up to and including the first _ ). #运算符从扩展中删除与*_匹配的最短前缀(可以是直到第一个_ ,包括第一个_任何字符)。

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

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