0

I have the following sed command:

sed -n '/^out(/{n;p}' ${filename} | sed -n '/format/ s/.*format=//g; s/),$//gp; s/))$//gp'

I tried to do it as one line as in:

sed -n '/^out(/{n;}; /format/ s/.*format=//g; s/),$//gp; s/))$//gp' ${filename}

But that also display the lines I don't want (those that do not match).

What I have is a file with some strings as in:

entry(variable=value)),
format(variable=value)),
entry(variable=value)))
out(variable=value)),
format(variable=value)),
...

I just want the format lines that came right after the out entry. and remove those trailing )) or ),

Lin
  • 966
  • 6
  • 20
  • I know that I can do it with grep, but I want to use a single command with a single execution (or a single grep, single awk or single sed. And for that I thought that sed would have smaller memory/cpu footprint. – Lin Apr 25 '16 at 18:56
  • the second sed command in your question works perfectly for the sample input you have given. – Niall Cosgrove Apr 25 '16 at 19:03
  • 1
    @Lin It would be easier for all if you put up sample input & output required. – Ani Menon Apr 25 '16 at 19:04

1 Answers1

1

You can use this sed command:

sed -nr '/^out[(]/ {n ; s/.*[(]([^)]+)[)].*/\1/p}' your_file

Once a out is found, it advanced to the next line (n) and uses the s command with p flag to extract only what is inside parenthesises.

Explanation:

  • I used [(] instead of \(. Outside brackets a ( usually means grouping, if you want a literal (, you need to escape it as \( or you can put it inside brackets. Most RE special characters dont need escaping when put inside brackets.
  • ([^)]+) means a group (the "(" here are RE metacharacters not literal parenthesis) that consists of one or more (+) characters that are not (^) ) (literal closing parenthesis), the ^ inverts the character class [ ... ]
Lars Fischer
  • 7,817
  • 3
  • 24
  • 31
  • Seems promissing =D just changing out for ^out, because I can find the out word inside some variable/value. – Lin Apr 25 '16 at 19:03
  • Your response fits perfect to the data I have provided above. (that I now noticed that isn't exactly my original source data). But is ok. I have made the necessary corrections to fit my real data. – Lin Apr 25 '16 at 19:05
  • @Lin changed the pattern between the `/../` – Lars Fischer Apr 25 '16 at 19:05
  • Why do you encapsulate the ( with [] ? What does the ^) after the group opening ( ? – Lin Apr 25 '16 at 19:12
  • @Lin I tried to explain it a bit more in detail. for more information about regular expressions, you could start at http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean/22944075#22944075 – Lars Fischer Apr 25 '16 at 19:25