0

I'm a beginner of bash.

Suppose I have a text file sample.txt, which contains

mercury
venus
earth
mars
jupiter
saturn
uranus
neptune
pluto

and two keywords earth and saturn.

The gold is to find the lines that contain the keywords (there is exactly one line that contains each of the keywords), and output all the lines in between, including both keywords lines.

Given the above keywords earth, saturn and input, the expected output is

earth
mars
jupiter
saturn

If possible, avoid regex. Is there anyway to do this?

MasterMind
  • 124
  • 12

3 Answers3

3

You can use either awk or sed:

Using awk:

awk '/earth/,/saturn/' sample.txt

Using sed:

sed -n '/earth/,/saturn/p' sample.txt
user5478656
  • 266
  • 1
  • 2
  • 9
0

You may want to visit Here for more examples and test cases.

awk '/earth/,/saturn/' planets.txt
    earth
    mars
    jupiter
    saturn

Or by sed

sed -n '/earth/,/saturn/p' planets.txt
earth
mars
jupiter
saturn
Community
  • 1
  • 1
P....
  • 17,421
  • 2
  • 32
  • 52
0
perl -lne 'print if(/earth/.../saturn/)' planets.txt

Another solution to get the data only when both the keywords exists.

 perl -lne '$f=1 if(/earth/);
            push @a,$_ if($f==1);
            if(/saturn/){print join "\n",@a;undef @a;$f=0}' 
            planets.txt
Vijay
  • 65,327
  • 90
  • 227
  • 319