sed 多个记住的模式

dav*_*ide 3 regex bash sed

我有一系列类似于以下的字符串(但它们可能更复杂):

echo "I am 17 y/o, I live at 44 Main street, and my mother is 69years old"
Run Code Online (Sandbox Code Playgroud)

我只想打印第一个图案 (17)。我尝试使用 sed 使用:

sed 's/.*\([0-9][0-9]\)[ y].*/\1/'
Run Code Online (Sandbox Code Playgroud)

但是每次列出最后一个模式时它都会打印我(在这种情况下为 69)。

如何强制 sed 打印第一个或第二个模式?

谢谢!

gle*_*man 5

使用grep -o提取的数字,它们存储在一个数组,那么你可以选择你想要哪一个:

line="I am 17 y/o, I live at 44 Main street, and my mother is 69years old" ^C

numbers=( $(grep -o '[[:digit:]]\+' <<< "$line") )

# index from the start of the array
echo "First: ${numbers[0]}"
echo "Second: ${numbers[1]}"
# index from the end of the array
echo "Last: ${numbers[-1]}"
echo "2nd Last: ${numbers[-2]}"
Run Code Online (Sandbox Code Playgroud)
First: 17
Second: 44
Last: 69
2nd Last: 44
Run Code Online (Sandbox Code Playgroud)