0

Given a file TestData.txt containg lines, where junk may be repeated N or more times, and the position of the line "Model=Default" is not fixed

...
junk
junk

Model="C"
junk
junk
Size="81"
junk

Model="Default"   <---- Start of "Default" block
junk
...
junk
Size="47"         <---- Required value of size (first "Size=" line after "Default")
junk
junk

Model="A"
junk
Size="22"
junk
junk

Model="T"
junk
junk
Size="32"
junk
...

and wishing to extract the value of Size for the Default case, the following works by printing the lines between the matches and then applying a second sed command to do the substitution to extract the value of size.

sed -ne '/="Default"/,/Size=/p' TestData.txt | sed -ne 's|Size="\([1-9][0-9]*\)"|\1|p'

This prints 47, the required value of the "Size" parameter from the "Default" section.

Can the two sed operations be combined into a more efficient single sed invocation?

(This is a simplified form of the actual task which is to extract, with more complicated regexps, a single value from a configuration file where there are multiple blocks containing a "size" designation.)

2
  • You could use tail to print the last line of your first sed expression? Jan 23, 2017 at 2:35
  • Not quite because that would print out Size="47" and I need to get the actual number 47 and not the string. The "bare" number is going to be used further on in the script in an "expr" calculation.
    – J G Miller
    Jan 23, 2017 at 4:13

1 Answer 1

1

You should be able to add the second filter as a subexpression between braces

sed -ne '/="Default"/,/Size=/ {s/Size="\([1-9][0-9]*\)"/\1/p}' TestData.txt

or POSIXly

sed -ne '/="Default"/,/Size=/ {s/Size="\([1-9][0-9]*\)"/\1/p
}' TestData.txt

See Editing Commands in sed

[2addr] {function
function
...
}

Execute a list of sed functions only when the pattern space is selected. The list of sed functions shall be surrounded by braces and separated by newlines, and conform to the following rules. The braces can be preceded or followed by blanks. The functions can be preceded by blanks, but shall not be followed by blanks. The right-brace shall be preceded by a newline and can be preceded or followed by blanks.

1
  • Thanks for the explanation with the quote from the manual page and this will be useful for similar problems in the future.
    – J G Miller
    Jan 23, 2017 at 3:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .