简体   繁体   中英

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.

I have to truncate the first part "YYYYMMDD_" and leave in a $new_var "charcharchar...charchar.ext" .

I can't use "bash expansions" like ${string:position} because I'm into emulated environment (Cygwin)

thanks.

You tagged the question with awk, so here is an example with awk:

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

This is easier done using 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 _ ).

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