In the the below text file (someString.text), I want to grep all lines with .sh in it. ie. Only the lines mysript.sh and anotherscript.sh should be returned.
My below attempts failed.
I gather that in regular expression world, dot (.) is the wild card for any single character . So, what is the workaround ?
The grep regular expression must be quoted. The dot has a special meaning ("any character") so it must be escaped with a back slash to use its literal meaning. try:
grep '\.sh$' file
The dollar sign signifies that the match must be at the end of the line.
It might be better to quote the string you are searching for. The version grep *.sh someString.text could yield different results based on other files in the directory because the shell will assum you want to expand the * character to match all files that finish sh , so your command executed could end up being:-
This would mean it would search for 1sh in all the other files listed, which probably is not what you want.
Additionally, the dot is a special character that matches any single character. That might seem odd, but you might want to match A..B to get A01B [/ICODE], A02B , A17B etc. so to ensure it is the literal character dot, you need to use a backslash \ to escape it.
With quoting, it might help a little, but you need to be clear on what you are searching for, so:-
If you are looking for the literal string .sh then try grep '\.sh' someString.text
If you are looking for the literal string .sh at the end of the line, try grep '\.sh$' someString.text
In the latter, the $ in this case marks/anchors the search to the end of line. There could be other cases, such as .sh followed by a space, tab, hash etc., depending on the whole content of your file.
Does this do what you need, or are there other conditions to consider?
Another option is to use a literal string match (so the are no special meaning to characters) with the -F parameter. If .sh always only occurs at the end of the line anyway, you could also try: