From efe1e1543c409504752f8d240d3ea41af3b8fddf Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sun, 27 Feb 2022 15:15:51 -0800 Subject: [PATCH] =?UTF-8?q?doc:=20more=20on=20leading=20=E2=80=98-?= =?UTF-8?q?=E2=80=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * doc/grep.texi (Usage): Expand on leading ‘-’ problems (Bug#54174). --- doc/grep.texi | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/doc/grep.texi b/doc/grep.texi index ebbefda..f0ea1c3 100644 --- a/doc/grep.texi +++ b/doc/grep.texi @@ -1719,25 +1719,39 @@ grep -r --include='*.c' 'hello' /home/gigi @item What if a pattern or file has a leading @samp{-}? +For example: + +@example +grep "$pattern" * +@end example + +@noindent +can behave unexpectedly if the value of @samp{pattern} begins with @samp{-}, +or if the @samp{*} expands to a file name with leading @samp{-}. +To avoid the problem, you can use @option{-e} for patterns and leading +@samp{./} for files: @example -grep -- '--cut here--' * +grep -e "$pattern" ./* @end example @noindent -searches for all lines matching @samp{--cut here--}. -Without @option{--}, -@command{grep} would attempt to parse @samp{--cut here--} as a list of -options, and there would be similar problems with any file names -beginning with @samp{-}. +searches for all lines matching the pattern in all the working +directory's files whose names do not begin with @samp{.}. +Without the @option{-e}, @command{grep} might treat the pattern as an +option if it begins with @samp{-}. Without the @samp{./}, there might +be similar problems with file names beginning with @samp{-}. -Alternatively, you can prevent misinterpretation of leading @samp{-} -by using @option{-e} for patterns and leading @samp{./} for files: +Alternatively, you can use @samp{--} before the pattern and file names: @example -grep -e '--cut here--' ./* +grep -- "$pattern" * @end example +@noindent +This also fixes the problem, except that if there is a file named @samp{-}, +@command{grep} misinterprets the @samp{-} as standard input. + @item Suppose I want to search for a whole word, not a part of a word? -- 2.32.0