Use grep for a long line to get the part of the line

2

I want to search in a long sentence (more than 1024 letters).

I have one text file (test.txt) which has one long sentence, like this:

afdafglwqgkjrldjl;ewqje;'k;g;je;;;fdsgalsdkf;akslg;safdas.....dasfsd

Now I want to check which line contains the word saf. This command just shows the whole sentence:

less test.txt | grep saf

Is it possible to get a part of the sentence or should I use a command other than grep?

whitebear

Posted 2018-10-19T14:51:43.257

Reputation: 273

grep -o 'saf' text.text? – Cyrus – 2018-10-19T14:54:15.037

THanks! It shows the matched point. however is it possible to show the a few letters before and after of matches??? – whitebear – 2018-10-19T14:56:49.900

grep -o '.\{0,3\}saf.\{0,3\}' text.text – this will include up to three characters before and up to three characters after. But if there is a second saf and it begins within these "three characters after" then it won't be matched separately. – Kamil Maciorowski – 2018-10-19T15:48:16.740

@KamilMaciorowski It's perfect what I want. it works prety well – whitebear – 2018-10-23T21:44:57.083

Answers

2

Not exactly what you were looking for: show the matching lines and highlight the occurences in those lines:

grep --color 'saf' test.txt

Options for searching saf and displaying up to 15 characters before and after the occurences found using:

  • the standard regex syntax, first mentioned by @kamil-maciorowski in his comment on the question:

    grep -o '.\{0,15\}saf.\{0,15\}' test.txt | grep saf --color
    
  • Perl-compatible regex syntax with the -P option, if available:

    grep -o -P '.{0,15}saf.{0,15}' test.txt | grep --color saf
    
  • extended regex syntax with the -E option, if your grep has no -P option (like e.g. on macOS):

    grep -o -E '.{0,15}saf.{0,15}' test.txt | grep --color saf
    

t0r0X

Posted 2018-10-19T14:51:43.257

Reputation: 144

See my comment under the question. If you add a remark to your answer about a possibility of not matching all saf-s, I will upvote it and delete my comment. – Kamil Maciorowski – 2018-10-19T15:53:58.820

Thanks @t0r0X , I tried your one too . my grep doens't have -P option somehow. and backslash before { is needed. But I appreciate your answer too. – whitebear – 2018-10-23T21:46:15.173

@whitebear Indeed, not every grep has -P, but there's yet another variant, I'll update again my answer. – t0r0X – 2018-10-24T00:33:19.243

@kamil-maciorowski I will look into it. – t0r0X – 2018-10-24T16:04:57.907