使用 grep 从另一个中提取字符串

extract string from another using grep

我是 shell 开发新手。我想使用 grep 实用程序

从 uci 命令结果中提取 cfgxxxx
#uci show -X fire |grep "fire\.[^.]\+\.instance

fire.cfg1a3837.instance=1
fire.cfg1c3837.instance=2
fire.cfg243837.instance=3
fire.cfg263837.instance=4
fire.cfg283837.instance=5
fire.cfg2a3837.instance=6
fire.cfg2c3837.instance=7
fire.cfg2e3837.instance=8
fire.cfg303837.instance=9
fire.cfg323837.instance=10

但是下面的命令没有提取准确的值

#uci show -X fire |grep "fire\.[^.]\+\.instance=1" | cut -d. -f2
cfg1a3837  --> instance=1
cfg323837  --> instance=10

如何只提取实例号1

uci show -X fire |grep "fire\.[^.]\+\.instance=1$" | cut -d. -f2

您需要添加一个 $ 否则 =1=10 将被相同对待。

您可以只使用 awk 并将 2 个命令缩减为一个:

uci show -X fire | awk -F '\.' '=="fire"{print }'
cfg1a3837
cfg1c3837
cfg243837
cfg263837
cfg283837
cfg2a3837
cfg2c3837
cfg2e3837
cfg303837
cfg323837

你也可以使用这个grep -oP:

uci show -X fire | grep -oP "fire\.\K[^.]+(?=\.instance)"