I have file.txt from which I need to grep first occurrence of a pattern. How can I grep and get matched string only ‘:whitespace’ and ‘end of line’
I m trying below command
cat file.txt | grep -m1 -P "(:s+).*ccas-apache$"
But it gives me
name: nginx-ccas-apache
and I want is
nginx-ccas-apache
file.txt
pod: nginx-ccas-apache-0
name: nginx-ccas-apache
image: myregnapq//ccas_apache
name: nginx-filebeat
pod: nginx-ccas-apache-1
name: nginx-ccas-apache
image: myregnapq/ccas_apache
name: nginx-filebeat
5
Answers
Using
grep
You can use
awk
, too:Details:
-F:
– a colon is used as a field separator:[[:space:]].*ccas-apache$
– searches for a line with:
, a whitespace, then any text,ccas-apache
at the end of the string, and once foundsub(/^[[:space:]]+/, "", $2)
– remove the initial whitespaces from Field 2print $2
– then print the Field 2 valueexit
– stop processing the file.See the online demo:
Output:
nginx-ccas-apache
Another approach using
sed
:Explanation
-En
Use extended regexp with-E
and prevent the default printing of a line by sed with-n
/^[[:space:]]+name:[[:space:]](.*ccas-apache)$/
The pattern that specifies what to matchIf the previous pattern matched, run commands between the curly brackets
s//1/p
Use the last matched pattern with//
and replace with group 1. Then print the pattern space withp
q
exit sedThe regex matches:
^
Start of string[[:space:]]+name:[[:space:]]
Matchname:
with leading spaces and single space after(.*ccas-apache)
Capture group 1, match optional chars andccas-apache
$
End of stringOutput
Note that you don’t have to use
cat
See an online demo.
INPUT
CODE
enter any properly-escaped pattern for
__
that includes the string tail$
gawk
,mawk-1
,mawk-2
, ormacos nawk
OUTPUT
GENERIC SOLUTION
FS
CODE
OUTPUT
With your shown samples please try following
awk
code.Explanation: Simple explanation would be, setting field separator as colon followed by space(1 or more occurrences). In main program checking condition if first field matches regex starts with space followed by name AND 2nd field matches regex
^[^-]*-ccas-apache$
then printing 2nd field of that line and `exit from program.