Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I try to search for lines that start with "1" using

ls -1 | grep ^1*

but it returns lines that do not start with 1. What I am missing here?

share|improve this question
    
Just another note: If you want to use grep to limit ls output, you will run into problems if filenames contain some weird characters, such as newlines... Many other commands (somehow not ls, at least not the version that I have to check) have a option to give null separated output, which you can then safely process with grep -z –  Gert van den Berg Dec 31 '12 at 6:34
    
Thanks, @GertvandenBerg! What problems can some weird characters such as newlines cause to grep? What commands give null separated output? –  Tim Dec 31 '12 at 12:32
    
find with -print0, most other GNU tool have a -0 or -z option. (sort, xargs, etc as well). If the filenames contain newlines, the it would be impossible to know if two lines are a filename containing a newline or two seperate filenames. –  Gert van den Berg Jan 2 '13 at 6:48

4 Answers 4

up vote 16 down vote accepted

Your regular expression doesn't mean what you think it does. It matches all lines starting (^) with one (1) repeated zero or more (*) times. All strings match that regular expression. grep '^1' does what you want.

share|improve this answer

Although this doesn't answer your question, this is a better solution to what appears to be your goal:

ls -ld 1*

You can use a shell glob to list all files that start with 1. Note that * has a different meaning in shell globbing than regular expressions.

share|improve this answer
    
Thanks! +1. How does * have different meaning in shell globbing and in regular expressions? –  Tim Dec 31 '12 at 3:33
    
In a shell glob * is a wildcard meaning "0 or more of any character". The regex meaning is explained in otokan's answer. –  jordanm Dec 31 '12 at 5:10

^1.* matches the whole line, or just as said above, ^1 got the string contained in the line.

different styles of regex uses different symbols representing chars, some options specify which style you want. and different options specify whether you want to match the whole line, or just part of it, or the whole input as one string.

share|improve this answer

Did you try the following?

 ls -1 | grep "^1"

That is, remove the *, which basically tells grep, find zero or more occurances of the ^1 expression. In other words: match the lines that start with a 1, or not.

share|improve this answer
    
Thanks, Bernhard! +1 –  Tim Dec 30 '12 at 22:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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