How to search and extract string from command output?
Using sed
$ command | sed -n 's/.*text4://p'
"lkpird sdfd"
-n
tells sed not to print unless we explicitly ask it to. s/.*text4://
tells sed to remove any text from the beginning of the line to the final occurrence of text4:
. If such a line is found, then the p
tells sed to print it.
Using grep -P
$ command | grep -oP '(?<=text4:).*'
"lkpird sdfd"
-o
tells grep to print only the matching part. (?<=text4:).*
matches any text that follows text4:
but does not include the text4:
.
The -P
option requires GNU grep. Thus, it will not work with busybox's builtin grep
, nor with the default grep
on BSD/Mac OSX systems.
Using awk
The original grep-awk solution can be simplified:
$ command | awk -F': ' '/text4: /{print $2}'
"lkpird sdfd"
Using awk (alternate)
$ command | awk '/text4:/{sub(/.*text4:/, ""); print}'
"lkpird sdfd"
/text4:/
selects lines that contain text4:
. sub(/.*text4:/, "")
tells awk to remove all text from the beginning of the line to the last occurrence of text4:
on the line. print
tells awk to print those lines.
With grep
and its PCRE support and \K
notify.
command |grep -Po 'text4: \K.*'