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?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
Method 2
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.
Method 3
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.
Method 4
^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.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0