我有一个脚本,运行后将显示:
The square 1 with the name Square with area 10 is created
The square 2 with the name Box with area 20 is created
The circle with the name Spinny with area 22 is not created
The rectangle with the name Tri with area 30 is created.
如何检索区域和创建之间的所有数字并将其存储到数组中?
存储的数组将是:
10
20
30
棘手的部分是,我不能只找到第一个数字,因为平方 (1) 将被读取,我也不能取"面积"和"是"之间的数字,因为它可能会采用未创建的形状。知道怎么做吗?
使用 grep
:
$ cat testfile
The square 1 with the name Square with area 10 is created
The square 2 with the name Box with area 20 is created
The circle with the name Spinny with area 22 is not created
The rectangle with the name Tri with area 30 is created.
$ grep -Eo 'area [0-9]+ is created' testfile | grep -Eo '[0-9]+'
10
20
30
注意 POSIX grep 不支持 -o
,但这应该适用于 BSD 和 GNU grep。
awk
awk '/area [[:digit:]]+ is created/{ print $(NF-2); }'
打印匹配行上的倒数第三个字段。
array=( $(awk '/area [[:digit:]]+ is created/{ print $(NF-2); }' <<< "$input") )
printf '%sn' "${array[@]}"
10
20
30
纯粹的狂欢
array=()
while read -a line; do
if [[ "${line[@]: -2:1}" = is && "${line[@]: -1}" = created ]]; then
array+=( "${line[@]: -3:1}" )
fi
done <<< "$input"
printf '%s, ' "${array[@]}" # Will output 10, 20 if there's a period on the last line...
array=( $(sed -n 's/.*with area ([0-9][0-9]*) is created.*/1/p' data) )
array=( ... )
表示法是 bash
中的数组赋值。 $(...)
是命令替换。 默认情况下不打印 sed
命令,但是当一行与"创建区域 XX"匹配时(其中 XX 是一个或多个数字的数字),则该行将替换为 XX 的值并打印。
使用 gnu grep (Lookforward and Lookback Zero-length Assertions)
grep -Po '(?<=area )[0-9]* (?=is created)' file
使用 sed
sed -n 's/.* area ([0-9]*) is created.*/1/p' file