0

Let's say I want to search a file for a string that begins with a dash, say "-something":

grep "-something" filename.txt

This throws an error, however, because grep and other executables, as well as built-ins, all want to treat this as a command-line switch that they don't recognize. Is there a way to prevent this from happening?

ErikE
  • 129
  • @Freddy Do all executables and built-ins accept --? – ErikE Nov 08 '19 at 01:45
  • ErikE take it easy ... Maybe @Freddy haven't read my answer yet. Give it some minutes .... –  Nov 08 '19 at 02:11
  • @ErikE No, not all programs accept the --, there are exceptions (see here). The -e switch is also mentioned in the comments section. I flagged this Q as duplicate, because I (still) think it is. You asked for a generic way and the -- is a common way to handle such arguments. But that doesn't necessarily mean that this is the only way. – Freddy Nov 08 '19 at 02:21

2 Answers2

5

For grep use -e to mark regex patterns:

grep -e "-something" filename.txt

For general built-ins use --, in many utilities it marks "end of options" (but not in GNU grep).

  • grep -- "-something" filename.txt would have worked as well (due to GNU grep's first synopsis form), but since there is a -e option for giving an expression, it might be better to use that. – Kusalananda Nov 08 '19 at 06:57
2

For grep you can also change the regexp so it doesn't actually begin with hyphen, by using a trivial character list:

 grep '[-]something'

This trick^Wmethod was traditionally used to avoid false matches in ps:

ps -f | grep myprog 
# lists both the process(es) running myprog AND the grep process
# making it harder to do things like choose the right process to kill(1)

ps -f | grep '[m]yprog'
# lists only the 'real' processes because [m]yprog matches "myprog" 
# but [m]yprog does NOT match "grep [m]yprog"

but in the modern era just using pgrep (or pkill) is easier.