-1

I have several files, with different names. no specific format for them. But all are .txt. For example:

example.txt
flower.txt
abc.com.txt

They are in the same directory. I want to search for a string line in all the files, e.g. <html>. Then, if found, I want to extract the line where the string found. Then I want to save the search results in a results.txt file as follows:

file name,line

For example, if the string <html> was found in example.txt and abc.com.txt, then the results file will be:

example.txt,<html>[the rest of the line where html is found]
abc.com.txt,<html>[the rest of the line where html is found]

How can I achieve this in linux?

  • How about filename.txt:line-containing-pattern? – roaima Mar 1 at 19:40
  • And you seem to want <html> followed by the remainder of the line. What about any text on the line before the matching word? – roaima Mar 1 at 19:41
  • @steeldriver I prefer comma. But can be anything I guess. Yes, if a match is found, I want the whole line. – user9371654 Mar 1 at 21:02
  • @roaima It think your suggested format works too. But I can not get why not comma? – user9371654 Mar 1 at 21:03
  • @roaima The keyword I search about is not necessarily <html> it can be other words. – user9371654 Mar 1 at 21:03
1

The grep command will do exactly what you have accepted in the comments. (If you can guarantee there is more than one file, then you can omit -H.)

grep -FH '<html>' *

The -F flag switches off Regular Expression processing, so the string is treated as a literal.

  • How to write the file name where the keyword is found? and the whole line? In an append way? I mean I want all the results in one file. – user9371654 Mar 1 at 21:27
  • That's what it does. Just redirect the output to the target file. – roaima Mar 1 at 21:31

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.