Grep a line which start and end with a pre defined character

I am trying to fetch a line from a file file.txt which looks like this:

>This is line 1.</li>
>This is line 2.</li>
>This is line 3.</li>
>This is line 4.</li>

I need to fetch content which starts with > and ends in </li> so the output will be This is line 1. This is line 2. and so on. I have looked into this in forum but didnt found solution. This solution also didnt worked.

I ultimately have to fetch some lines from a webpage. So first I will curl webpage and then use grep command to grep that line which starts with > and ends in </li>.

Thanks.!

1

2 Answers

This should be enough:

grep '^>.*</li>$' input-file

The ^ and $ ensure that those parts are anchored at the start and end of the lines respectively.

You can also do:

grep -x '>.*</li>' input-file

-x looks for an exact match: the whole line should match the pattern (which implies ^ and $ is wrapped around the pattern).

5

This is the input file:

$ cat /tmp/tmp.txt
>This is line 1.</li>
invalid line 1
>This is line 2.</li>
>This is line 3.</li>
invalid line 2
>This is line 4.</li>
last invalid line

Using grep and awk to extract the strings you want:

$ cat /tmp/tmp.txt | grep -E '>*</li>' | awk -F\> '{ print $2 }' | awk -F\< '{ print $1 }'
This is line 1.
This is line 2.
This is line 3.
This is line 4.
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like