What command must be used to grep items between 2 matching patterns from a file.
My file has lines like:
abc def ghi
abc bcd def (task Name: example)
##some other similar lines##
I need the data between Name: and ‘)’
I tried with the command
cat script.log | sed 's/Name:\(.*\)\)/\1/gp'
This command is not providing me with required result. Please guide me with this.
Also, is it possible to use $Name in place of “Name:” (using a variable that substitutes the original value)
Something like:
should do the job.
The biggest mistake that you had in your original expression is that you escaped the second parenthesis. When I run your snippet, I get an error:
Even if you correct that, you will find that sed prints every line by default. Here is what the expression that I built up does.
Sed expressions take the form of
[address[,address]]function[arguments]. Your expression did not include either of the optional address elements. I included a single address (/Name:/) which matches any line that contains “Name:”. The function is the substitution function which requires two arguments – (1) a search pattern and (2) a replacement expression. The search pattern matches the entire line and extracts the segment of the line following “Name:” that contains zero or more characters until the first parenthesis. The “escaped” parentheses define the capture group and the unescaped one terminates the capture. The pattern includes the rest of the line (e.g.,.*$). Since the entire line is matched, it will be replaced by the replacement expression which contains only the captured portion.Putting this all together, the simple sed statement matches any line containing “Name:” and replaces the entire line with the characters between
Name:and the first left parenthesis ()). The-nflag and the addition of thepflag ensures that only the matched lines are printed.