Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I need to search through a folder of files and copy all text that begins with a variable.

So for example:

Files A.txt,B.txt,C.txt, and D.txt contain the strings "Hello1", "Hello2", "Hello3", and "Hello4" respectively. I need to be able to search for all words that begin with "Hello" and output the result.

In this particular case A.txt,B.txt,C.txt, and D.txt would be searched and the output would be


I've looked around and found the following which allows me to export all files containing the text, however I'm not sure how or if this can be adapted for what I need.

grep -l Hello *.txt
share|improve this question
up vote 3 down vote accepted

You probably want grep -ohw 'Hello[0-9]*' *.txt.

  • -o only outputs the matching part of the line
  • -h makes grep suppress filename output
  • -w makes grep search for whole words only, so a Hello1Hello2 would not be matched (it would be matched twice without -w though)

You need to adjust the pattern, since a literal Hello will only match Hello and subsequently just output that. Since you want to match Hello1 through Hello5 (or even Hello123), you need multiple digits ([0-9]*).

Don't forget to quote the pattern so the * is not expanded by the shell.

share|improve this answer
+1 for a right answer but I think the OP does not want the -o since he says "all text that begins with a variable." – terdon Jul 3 '13 at 17:46
Could be. Their example is ambiguous in that regard. Let's see. – slhck Jul 3 '13 at 17:47
This is great, thank you! My example was a little simpler than what I actually needed. I ended up going with this. grep -ohw 'FDRLocalizedString(@".*"' *.m – Brandon Jul 3 '13 at 19:02

This looks for words beginning with a variable.

grep -ho "\\<${var}[^[:blank:]]*" *.txt

grep's \< is the "start of word" anchor.

I assume that your words are blank delimited, so the rest of the word is non-blank characters. You can change this to numbers ([0-9]*) or perl-like "word characters" ([[:alnum:]_]*) easily enough.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .