在 bash 脚本中拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7883369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:59:38  来源:igfitidea点击:

Splitting a string in a bash script

regexbash

提问by Ian Burris

Possible Duplicate:
Split string based on delimiter in bash?

可能的重复:
基于 bash 中的分隔符拆分字符串?

I have a bunch of files named test<numbers or letters>.<number>.outso like test1.1024.outor test2.2.out. Is there some way I can use a regular expression like ^test.*?..(.*).out$to parse out the middle number on each file and then be able to access the group?

我有一大堆命名的文件中test<numbers or letters>.<number>.out如此喜欢test1.1024.outtest2.2.out。有什么方法可以使用正则表达式^test.*?..(.*).out$来解析每个文件的中间数字,然后才能访问该组?

回答by rob mayoff

for f in test*.out; do
  number=${f#test*.}
  number=${number%.*}
  echo $f has middle number $number
done

回答by Swiss

sed -r 's/^test[[:alnum:]]*\.([[:digit:]]+)\.out$//'

Alternatively (A shorter version of the BASH for loop):

或者(BASH for 循环的较短版本):

awk -F '.' '{print }'

回答by Niall Byrne

Depending on the version of Bash this could work too:

根据 Bash 的版本,这也可以工作:

 test=test1.1024.out
 if [[ $test =~ ^test[A-Za-z0-9]+\.([0-9]+)\.out$ ]]; then
      echo ${BASH_REMATCH[1]}
 fi