Skip to content
Advertisement

Finding a string between two lines in a file using linux commands

I have a file, file.txt, like this:

start cal
end cal
start eff
end eff
start cal
error
end cal
start dod
end dod

What I want to get is the line between the last set of ‘start cal’ and ‘end cal’. I am using tac and grep to do it. But in vain. Any help please? Below is my code:

tac file.txt | grep -m1 'start cal*end cal'

What am I doing wrong? For the example above, I need the command to return ‘error’.

Advertisement

Answer

Grep is not good tool for this task. It does line based matching. You can consider using awk.

if you have single line in between:

tac file|awk '/end cal/{p=1;next}/start cal/{exit}p'

If it could be multiple lines:

tac file|awk '/end cal/{p=1;next}/start cal/{exit}p'|tac

It outputs:

error
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement