0

I have a dictionary (not python dict) consisting of many text files like this:

##Berlin                
-capital of Germany         
-3.5 million inhabitants

##Earth           
-planet

How can I show one entry of the dictionary with the facts?

Thank you!

kame
  • 20,848
  • 33
  • 104
  • 159

3 Answers3

1

You can't. grep doesn't have a way of showing a variable amount of context. You can use -A to show a set number of lines after the match, such as -A3 to show three lines after a match, but it can't be a variable number of lines.

You could write a quick Perl program to read from the file in "paragraph mode" and then print blocks that match a regular expression.

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
0

as andy lester pointed out, you can't have grep show a variable amount of context in grep, but a short awk statement might do what you're hoping for.

if your example file were named file.dict:

awk -v term="earth" 'BEGIN{IGNORECASE=1}{if($0 ~ "##"term){loop=1} if($0 ~ /^$/){loop=0} if(loop == 1){print $0}}' *.dict

returns:

##Earth
-planet

just change the variable term to the entry you're looking for.

assuming two things:

  1. dictionary files have same extension (.dict for example purposes)
  2. dictionary files are all in same directory (where command is called)
nullrevolution
  • 3,937
  • 1
  • 18
  • 20
  • is it all files in the folder that you're searching? if so, just change the last word from `*.dict` to `*` and it will search all files in that folder. – nullrevolution Dec 07 '12 at 14:21
0

If your grep supports perl regular expressions, you can do it like this:

grep -iPzo '(?s)##Berlin.*?\n(\n|$)'

See this answer for more on this pattern.

You could also do it with GNU sed like this:

query=berlin
sed -n "/$query/I"'{ :a; $p; N; /\n$/!ba; p; }'

That is, when case-insensitive $query is found, print until an empty line is found (/\n$/) or the end of file ($p).

Output in both cases (minor difference in whitespace):

##Berlin
-capital of Germany
-3.5 million inhabitants
Community
  • 1
  • 1
Thor
  • 45,082
  • 11
  • 119
  • 130
  • @kame: you need to tell sed what files to work on, try appending an asterisk (`*`) to the command. – Thor Dec 08 '12 at 11:33