Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String UNIX中的字符串操作_String_Bash_Unix - Fatal编程技术网

String UNIX中的字符串操作

String UNIX中的字符串操作,string,bash,unix,String,Bash,Unix,我有一个脚本,运行后将显示: 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. 如何检索

我有一个脚本,运行后将显示:

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 在匹配行上打印从第三个字段到最后一个字段

array=( $(awk '/area [[:digit:]]+ is created/{ print $(NF-2); }' <<< "$input") )
printf '%s\n' "${array[@]}"
10
20
30
array=($(awk'/area[[:digit:]]+/{print$(NF-2);}'使用gnu grep(前向和后向零长度断言)


array=(…)
符号是
bash
中的数组赋值。
$(…)
是命令替换。
sed
命令默认不打印,但当一行与“创建区域XX”匹配时(其中XX是一个或多个数字的数字),然后该行被替换为XX值并打印。

@kojiro,谢谢你的评论。我在答案中添加了你的评论。谢谢,-o是我丢失的键。最后一行是否真的以句号结尾,而所有其他行都没有?不是真的..哈哈,忽略句号
array=( $(awk '/area [[:digit:]]+ is created/{ print $(NF-2); }' <<< "$input") )
printf '%s\n' "${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...
grep -Po '(?<=area )[0-9]* (?=is created)' file
sed -n 's/.* area \([0-9]*\) is created.*/\1/p' file
array=( $(sed -n 's/.*with area \([0-9][0-9]*\) is created.*/\1/p' data) )