简体   繁体   中英

Grep variable for string in bash

We'd like to search for clid=* (* stands for an number) in the following $test variable:

Welcome to the TeamSpeak 3 ServerQuery interface, type "help" for a list of commands and "help <command>" for information on a specific command.

error id=0 msg=ok

error id=0 msg=ok

cluid=something2384fjdfkj clid=1 name=me

error id=0 msg=ok

Final result should be clid=1 .

Use the following egrep command:

egrep -o '\bclid=[0-9]+\b' testfile

-o option, tells to print only matched substrings

\\b - word boundary

This will print clid followed by one or more number:

grep -oP 'clid=\d+' inputfile

Or if it the input is from variable then :

echo  $test  |grep -oP 'clid=\d+'

Bash 有所谓的here 字符串,它允许您将变量的内容提供给 grep,而无需echo或管道:

grep -Eo 'clid=[0-9]+' <<< "$test"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM