0

I tried several commands and read a few tutorials, but none helped. I'm using gnu sed 4.2.2. I just want to search in a file for:

func1(int a)
{

I don't know if it is the fact of a newline followed by "{" but it just doesn't work. A correct command would help and with an explanation even more. Thanks!

Note: After "int a)" I typed enter, but I think stackoverflow doesn't put a newline. I don't want confusion, I just want to search func1(int a)'newline'{.

veducm
  • 5,933
  • 2
  • 34
  • 40
  • Are you just trying to find the string, or replace it? If it's only find, I'd suggest taking a look at http://en.wikipedia.org/wiki/Grep. – Martin Jan 27 '14 at 19:35
  • Hi Martin, indeed I'm just trying to find. But I don't see how grep could help with the newline followed by "{". If you could give an example of command line I would enjoy because I really really can't figure out. – user3241815 Jan 27 '14 at 19:49
  • Try here: http://stackoverflow.com/questions/3717772/regex-grep-for-multi-line-search-needed – Martin Jan 27 '14 at 19:57
  • Have a look at this for sed: http://unix.stackexchange.com/a/26290/57753 – Jakub Kotowski Jan 27 '14 at 20:08

1 Answers1

3

sed -n '/func1/{N;/func1(int a)\n{/p}'

Explanation:

sed -n '/func1/{                         # look for a line with "func1"
                N                        # append the next line
                /func1(int a)\n{/p       # try to match the whole pattern "func1(int a)\n{"
                                         # and print if matched
               }'                        

With grep it would be for example:

grep -Pzo 'func1\(int a\)\n{'

but notice that thanks to -z the input to grep will be one large "line" that includes the newline characters too (that is unless the input contains null characters). Parenthesis have to be escaped in this case because it is a Perl regular expression (-P). -o makes grep print just the matched pattern.

Jakub Kotowski
  • 7,411
  • 29
  • 38
  • +1, and made it general match: sed -n '/func1/{N;/func1([^)]*)\s*\n\s*{/p}' file – BMW Jan 28 '14 at 01:50