简体   繁体   中英

BASH Script - Find Replace multiple values

I've got a very simple bash script which I'm passing values to

I want to strip the prefix from the value passed to the script.

The works and strips test- from the passed value..

IN=$1
arrIN=(${IN//test-/})
echo $arrIN

So test-12345 returns 12345

Is there anyway to amend this so it will remove either test- or local- ?

I've tried :

arrIN=(${IN//test-|local-/})

But that didn't work..

Thanks

如果要将“ test-”或“ local-”更改为“”,则可以使用以下命令:

awk '{gsub(/test-|local-/, ""); print}'

You can use sed and get the exact result

IN=$1
arrIN=$( echo $IN | sed 's/[^-]\+.//')
echo $arrIN

Try using sed as below:

IN=$1
arrIN=$(echo $IN | sed -r 's/test-|local-//g')
echo $arrIN

Here sed will search for "test-" or "local-" and remove them completely anywhere in the whole input.

You can do it with extglob activated:

shopt -s extglob
arrIN=(${IN//+(test-|local-)/})

From man bash :

  ?(pattern-list)  
         Matches zero or one occurrence of the given patterns  
  *(pattern-list)  
         Matches zero or more occurrences of the given patterns  
  +(pattern-list)  
         Matches one or more occurrences of the given patterns  
  @(pattern-list)  
         Matches one of the given patterns  
  !(pattern-list)  
         Matches anything except one of the given patterns 

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