如何将字符串的一部分提取到变量中?

Yul*_* Ao 11 bash string regular-expression

我有这样的文件中的一行:

attempting to create a 512^3 level (with Dirichlet BC) using a 16^3 grid of 32^3 boxes and 800 tasks...
Run Code Online (Sandbox Code Playgroud)

我想提取的512^3,16^3,32^3并800从它的四个数字分别为它们分配到四个变量level,grid,boxes和tasks用于其他用途。

我怎样才能做到这一点?

cho*_*oba 19

Bash 可以将正则表达式与=~操作符 in匹配[[ ... ]]:

#! /bin/bash

line='attempting to create a 512^3 level (with Dirichlet BC) using a 16^3 grid of 32^3 boxes and 800 tasks...'
num='([0-9^]+)'
nonum='[^0-9^]+'
if [[ $line =~ $num$nonum$num$nonum$num$nonum$num ]] ; then
    level=${BASH_REMATCH[1]}
    grid=${BASH_REMATCH[2]}
    boxes=${BASH_REMATCH[3]}
    tasks=${BASH_REMATCH[4]}
    echo "Level $level, grid $grid, boxes $boxes, tasks $tasks."
fi
Run Code Online (Sandbox Code Playgroud)

  • 哇,从来不知道 Bash 可以做这样的事情:) (2认同)