如何将grep match用作变量(而不是整行)

时间:2019-05-29 09:12:29

标签: linux bash shell

这是示例文件

[user@linux]$ cat DeviceA
DeviceA#sh ver
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

Version 15.1(4)M10将被高亮

[user@linux]$ egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

将grep输出用作变量var

[user@linux]$ var=$(egrep --color=auto 'Version (15.1\(4\)M7|15.1\(4\)M10|15.2\(1\)T4)' DeviceA)
[user@linux]$

打印变量var

[user@linux]$ echo $var
Cisco IOS Software, 1841 Software (C1841-ADVSECURITYK9-M), Version 15.1(4)M10, RELEASE SOFTWARE (fc2)
[user@linux]$

执行var时,我能否只获得Version 15.1(4)M10而不是将整个行作为echo $var

所需的输出

[user@linux]$ echo $var
Version 15.1(4)M10
[user@linux]$

2 个答案:

答案 0 :(得分:2)

如Jww所提到的,可以使用-o标志轻松实现:

命令行:

fgrep -o "Version 15.1(4)M10" testtttt.txt, or, for introducing variable handling:
echo $(fgrep -o "Version 15.1(4)M10" testtttt.txt)

在脚本中,您可能会执行类似的操作(未经测试):

var=$(fgrep -o "Version 15.1(4)M10" testtttt.txt)
echo $var

答案 1 :(得分:0)

尝试一下:

tmp="${var%,*}"           # remove last part after ,
echo "${tmp##*,}"         # print last part after ,