LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Searching a line (https://www.linuxquestions.org/questions/linux-newbie-8/searching-a-line-703660/)

iongrey 02-10-2009 11:35 AM

Searching a line
 
Greetings everyone,

I am doing some beginners practicing with searching files in Unix and am having trouble understanding how to search a line that starts with some alphanumeric character and ends with some alphanumeric character. For example the following lines:

Test Test1 Test2 Test3
Be3st Ce4st1 Fest2 Mest6

If I wanted to find the line that starts with T and ends with 3, how would I do that?

I tried egrep '^T ? 3$', grep '^[T-3$]' and other variants, but no luck.

Any help would be appreciated.

Thanks and please be kind.

David the H. 02-10-2009 12:28 PM

In regex, '.' (period) represents any single character. '*' means "match the preceding character (or character range) zero or more times", '?' means "match the preceding character zero or one times", and '+' means "match the preceding character one or more times. So what you want is probably something more like '^T.*3$' or '^T.+3$', depending on whether you expect anything to exist between the first and last characters (the second one would match "Test3", but not "T3").

You can specify a range of characters or numbers with brackets, so '^[a-zA-Z].+[0-9]$' will match any letter of the alphabet at the beginning of the line, followed by one or more characters of any type, and ending with any number.

There are some special character range types also, like [:alnum:], which represents any alphanumeric character. You can find these documented in the grep man page.

There are many good regular expression tutorials on the web. I very highly recommend taking the time to work through one. You'll be glad you did.

iongrey 02-10-2009 12:48 PM

Thanks David The H. for clarification! It really helped.

David the H. 02-10-2009 01:04 PM

No problem. By the way, you can use the -o option in grep/egrep to output only the matching strings, instead of the full line. Makes it easier to see what's actually going on.


All times are GMT -5. The time now is 11:14 AM.