IT 공부내용 정리/Linux

터미널 명령어 - grep 파일 내용 중에 찾고 싶은 값이 있다면

따뜻한 차가움 2025. 3. 6. 11:30

사용 버전 : Linux 우분투(레드햇 계열) 24.04.01 LTS 버전
사용한 시스템 지역/언어 : 대한민국/한글

man grep 원문

더보기

GREP(1)                          User Commands                         GREP(1)

NAME
       grep, egrep, fgrep, rgrep - print lines that match patterns

SYNOPSIS
       grep [OPTION...] PATTERNS [FILE...]
       grep [OPTION...] -e PATTERNS ... [FILE...]
       grep [OPTION...] -f PATTERN_FILE ... [FILE...]

DESCRIPTION
       grep  searches  for  PATTERNS  in  each  FILE.  PATTERNS is one or more
       patterns separated by newline characters, and  grep  prints  each  line
       that  matches a pattern.  Typically PATTERNS should be quoted when grep
       is used in a shell command.

       A FILE of “-”  stands  for  standard  input.   If  no  FILE  is  given,
       recursive  searches  examine  the  working  directory, and nonrecursive
       searches read standard input.

       Debian also includes the  variant  programs  egrep,  fgrep  and  rgrep.
       These   programs  are  the  same  as  grep -E,  grep -F,  and  grep -r,
       respectively.  These  variants  are  deprecated  upstream,  but  Debian
       provides  for  backward  compatibility.  For portability reasons, it is
       recommended to avoid the  variant  programs,  and  use  grep  with  the
       related option instead.

OPTIONS
   Generic Program Information
       --help Output a usage message and exit.

       -V, --version
              Output the version number of grep and exit.

   Pattern Syntax
       -E, --extended-regexp
              Interpret  PATTERNS  as  extended regular expressions (EREs, see
              below).

       -F, --fixed-strings
              Interpret PATTERNS as fixed strings, not regular expressions.

       -G, --basic-regexp
              Interpret PATTERNS  as  basic  regular  expressions  (BREs,  see
              below).  This is the default.

       -P, --perl-regexp
              Interpret   PATTERNS   as  Perl-compatible  regular  expressions
              (PCREs).  This option is experimental when combined with the  -z
              (--null-data)  option,  and  grep  -P  may warn of unimplemented
              features.

   Matching Control
       -e PATTERNS, --regexp=PATTERNS
              Use PATTERNS as the patterns.  If this option is  used  multiple
              times or is combined with the -f (--file) option, search for all
              patterns  given.   This  option can be used to protect a pattern
              beginning with “-”.

       -f FILE, --file=FILE
              Obtain patterns from FILE, one per line.  If this option is used
              multiple times or is combined with  the  -e  (--regexp)  option,
              search  for  all  patterns  given.  The empty file contains zero
              patterns, and therefore matches nothing.  If FILE is  -  ,  read
              patterns from standard input.

       -i, --ignore-case
              Ignore  case  distinctions  in  patterns and input data, so that
              characters that differ only in case match each other.

       --no-ignore-case
              Do not ignore case distinctions  in  patterns  and  input  data.
              This is the default.  This option is useful for passing to shell
              scripts  that  already use -i, to cancel its effects because the
              two options override each other.

       -v, --invert-match
              Invert the sense of matching, to select non-matching lines.

       -w, --word-regexp
              Select only those  lines  containing  matches  that  form  whole
              words.   The  test is that the matching substring must either be
              at the  beginning  of  the  line,  or  preceded  by  a  non-word
              constituent  character.  Similarly, it must be either at the end
              of the line or followed by  a  non-word  constituent  character.
              Word-constituent   characters   are  letters,  digits,  and  the
              underscore.  This option has no effect if -x is also specified.

       -x, --line-regexp
              Select only those matches that exactly  match  the  whole  line.
              For  a  regular  expression pattern, this is like parenthesizing
              the pattern and then surrounding it with ^ and $.

   General Output Control
       -c, --count
              Suppress normal output; instead print a count of matching  lines
              for  each  input  file.  With the -v, --invert-match option (see
              above), count non-matching lines.

       --color[=WHEN], --colour[=WHEN]
              Surround  the  matched  (non-empty)  strings,  matching   lines,
              context  lines,  file  names,  line  numbers,  byte offsets, and
              separators (for fields and groups of context lines) with  escape
              sequences  to display them in color on the terminal.  The colors
              are defined by the environment variable  GREP_COLORS.   WHEN  is
              never, always, or auto.

       -L, --files-without-match
              Suppress  normal  output;  instead  print the name of each input
              file from which no output would normally have been printed.

       -l, --files-with-matches
              Suppress normal output; instead print the  name  of  each  input
              file  from  which  output  would  normally  have  been  printed.
              Scanning each input file stops upon first match.

       -m NUM, --max-count=NUM
              Stop reading a file after NUM matching lines.  If NUM  is  zero,
              grep  stops  right  away  without reading input.  A NUM of -1 is
              treated as infinity and grep does not stop; this is the default.
              If the input is standard input from  a  regular  file,  and  NUM
              matching  lines are output, grep ensures that the standard input
              is positioned to  just  after  the  last  matching  line  before
              exiting,  regardless  of the presence of trailing context lines.
              This enables a calling process to resume a  search.   When  grep
              stops  after NUM matching lines, it outputs any trailing context
              lines.  When the -c or --count option is also  used,  grep  does
              not   output   a  count  greater  than  NUM.   When  the  -v  or
              --invert-match option is also used, grep stops after  outputting
              NUM non-matching lines.

       -o, --only-matching
              Print  only  the  matched  (non-empty) parts of a matching line,
              with each such part on a separate output line.

       -q, --quiet, --silent
              Quiet;  do  not  write  anything  to  standard   output.    Exit
              immediately  with  zero status if any match is found, even if an
              error was detected.  Also see the -s or --no-messages option.

       -s, --no-messages
              Suppress error messages about nonexistent or unreadable files.

   Output Line Prefix Control
       -b, --byte-offset
              Print the 0-based byte offset within the input file before  each
              line of output.  If -o (--only-matching) is specified, print the
              offset of the matching part itself.

       -H, --with-filename
              Print  the  file  name for each match.  This is the default when
              there is more than one file to search.  This is a GNU extension.

       -h, --no-filename
              Suppress the prefixing of file names on  output.   This  is  the
              default  when there is only one file (or only standard input) to
              search.

       --label=LABEL
              Display input actually  coming  from  standard  input  as  input
              coming  from  file  LABEL.  This can be useful for commands that
              transform a file's contents before  searching,  e.g.,  gzip  -cd
              foo.gz  |  grep  --label=foo -H 'some pattern'.  See also the -H
              option.

       -n, --line-number
              Prefix each line of output with the 1-based line  number  within
              its input file.

       -T, --initial-tab
              Make  sure  that the first character of actual line content lies
              on a tab stop, so that the alignment of tabs looks normal.  This
              is useful with options that prefix their output  to  the  actual
              content:  -H,-n,  and  -b.   In order to improve the probability
              that lines from a single file will all start at the same column,
              this also causes the line number and byte offset (if present) to
              be printed in a minimum size field width.

       -Z, --null
              Output a zero byte (the ASCII  NUL  character)  instead  of  the
              character  that normally follows a file name.  For example, grep
              -lZ outputs a zero byte after each  file  name  instead  of  the
              usual  newline.   This option makes the output unambiguous, even
              in the presence of file names containing unusual characters like
              newlines.  This option can  be  used  with  commands  like  find
              -print0,  perl  -0,  sort  -z, and xargs -0 to process arbitrary
              file names, even those that contain newline characters.

   Context Line Control
       -A NUM, --after-context=NUM
              Print NUM  lines  of  trailing  context  after  matching  lines.
              Places   a  line  containing  a  group  separator  (--)  between
              contiguous groups of matches.  With the  -o  or  --only-matching
              option, this has no effect and a warning is given.

       -B NUM, --before-context=NUM
              Print  NUM  lines  of  leading  context  before  matching lines.
              Places  a  line  containing  a  group  separator  (--)   between
              contiguous  groups  of  matches.  With the -o or --only-matching
              option, this has no effect and a warning is given.

       -C NUM, -NUM, --context=NUM
              Print NUM lines of output context.  Places a line  containing  a
              group separator (--) between contiguous groups of matches.  With
              the  -o  or  --only-matching  option,  this  has no effect and a
              warning is given.

       --group-separator=SEP
              When -A, -B, or -C are in use, print SEP instead of  --  between
              groups of lines.

       --no-group-separator
              When  -A, -B, or -C are in use, do not print a separator between
              groups of lines.

   File and Directory Selection
       -a, --text
              Process a binary file as if it were text; this is equivalent  to
              the --binary-files=text option.

       --binary-files=TYPE
              If  a  file's  data  or metadata indicate that the file contains
              binary data, assume that the file is  of  type  TYPE.   Non-text
              bytes  indicate  binary data; these are either output bytes that
              are improperly encoded for the current  locale,  or  null  input
              bytes when the -z option is not given.

              By  default,  TYPE  is  binary, and grep suppresses output after
              null input binary data  is  discovered,  and  suppresses  output
              lines that contain improperly encoded data.  When some output is
              suppressed,  grep  follows any output with a message to standard
              error saying that a binary file matches.

              If TYPE is without-match, when grep discovers null input  binary
              data  it  assumes that the rest of the file does not match; this
              is equivalent to the -I option.

              If TYPE is text, grep processes a binary  file  as  if  it  were
              text; this is equivalent to the -a option.

              When  type  is  binary,  grep  may  treat non-text bytes as line
              terminators even without the -z  option.   This  means  choosing
              binary  versus text can affect whether a pattern matches a file.
              For example, when type is binary the pattern q$  might  match  q
              immediately  followed  by  a  null byte, even though this is not
              matched when type is text.  Conversely, when type is binary  the
              pattern . (period) might not match a null byte.

              Warning:  The  -a  option might output binary garbage, which can
              have nasty side effects if the output is a terminal and  if  the
              terminal driver interprets some of it as commands.  On the other
              hand,  when  reading  files whose text encodings are unknown, it
              can  be  helpful  to  use  -a  or  to  set  LC_ALL='C'  in   the
              environment,  in  order to find more matches even if the matches
              are unsafe for direct display.

       -D ACTION, --devices=ACTION
              If an input file is a device, FIFO  or  socket,  use  ACTION  to
              process  it.   By  default,  ACTION  is  read,  which means that
              devices are read just as if they were ordinary files.  If ACTION
              is skip, devices are silently skipped.

       -d ACTION, --directories=ACTION
              If an input file is a directory, use ACTION to process  it.   By
              default,  ACTION is read, i.e., read directories just as if they
              were  ordinary  files.   If  ACTION  is  skip,   silently   skip
              directories.   If  ACTION  is recurse, read all files under each
              directory, recursively, following symbolic links  only  if  they
              are on the command line.  This is equivalent to the -r option.

       --exclude=GLOB
              Skip  any  command-line file with a name suffix that matches the
              pattern GLOB, using wildcard matching; a name suffix  is  either
              the  whole name, or a trailing part that starts with a non-slash
              character immediately after a  slash  (/)  in  the  name.   When
              searching  recursively, skip any subfile whose base name matches
              GLOB; the base name is the part after the last slash.  A pattern
              can use *, ?, and [...] as wildcards, and \ to quote a  wildcard
              or backslash character literally.

       --exclude-from=FILE
              Skip  files  whose  base name matches any of the file-name globs
              read from FILE  (using  wildcard  matching  as  described  under
              --exclude).

       --exclude-dir=GLOB
              Skip  any command-line directory with a name suffix that matches
              the  pattern  GLOB.   When  searching  recursively,   skip   any
              subdirectory whose base name matches GLOB.  Ignore any redundant
              trailing slashes in GLOB.

       -I     Process  a  binary  file as if it did not contain matching data;
              this is equivalent to the --binary-files=without-match option.

       --include=GLOB
              Search only files whose base name matches GLOB  (using  wildcard
              matching   as  described  under  --exclude).   If  contradictory
              --include and --exclude options are given, the last matching one
              wins.  If no --include or --exclude options  match,  a  file  is
              included unless the first such option is --include.

       -r, --recursive
              Read  all  files  under  each  directory, recursively, following
              symbolic links only if they are on the command line.  Note  that
              if   no  file  operand  is  given,  grep  searches  the  working
              directory.  This is equivalent to the -d recurse option.

       -R, --dereference-recursive
              Read all files under each directory,  recursively.   Follow  all
              symbolic links, unlike -r.

   Other Options
       --line-buffered
              Use  line  buffering  on  output.   This can cause a performance
              penalty.

       -U, --binary
              Treat the file(s) as binary.  By default, under MS-DOS  and  MS-
              Windows,  grep  guesses  whether  a  file  is  text or binary as
              described for the --binary-files option.  If  grep  decides  the
              file  is  a  text  file,  it  strips  the CR characters from the
              original file contents (to make regular expressions with ^ and $
              work  correctly).   Specifying  -U  overrules  this   guesswork,
              causing  all  files  to  be  read  and  passed  to  the matching
              mechanism verbatim; if the file is a text file with CR/LF  pairs
              at   the  end  of  each  line,  this  will  cause  some  regular
              expressions to fail.  This option has  no  effect  on  platforms
              other than MS-DOS and MS-Windows.

       -z, --null-data
              Treat  input  and  output  data  as  sequences  of  lines,  each
              terminated by a zero byte (the ASCII NUL character) instead of a
              newline.  Like the -Z or --null option, this option can be  used
              with commands like sort -z to process arbitrary file names.

REGULAR EXPRESSIONS
       A  regular  expression  is  a  pattern that describes a set of strings.
       Regular  expressions  are   constructed   analogously   to   arithmetic
       expressions, by using various operators to combine smaller expressions.

       grep understands three different versions of regular expression syntax:
       “basic”  (BRE), “extended” (ERE) and “perl” (PCRE).  In GNU grep, basic
       and extended regular expressions are merely different notations for the
       same pattern-matching functionality.  In other  implementations,  basic
       regular  expressions are ordinarily less powerful than extended, though
       occasionally it is the other way  around.   The  following  description
       applies  to extended regular expressions; differences for basic regular
       expressions  are  summarized   afterwards.    Perl-compatible   regular
       expressions   have  different  functionality,  and  are  documented  in
       pcre2syntax(3) and pcre2pattern(3), but work only if  PCRE  support  is
       enabled.

       The  fundamental building blocks are the regular expressions that match
       a single character.  Most characters, including all letters and digits,
       are regular expressions that match themselves.  Any meta-character with
       special meaning may be quoted by preceding it with a backslash.

       The period . matches any single character.  It is  unspecified  whether
       it matches an encoding error.

   Character Classes and Bracket Expressions
       A  bracket  expression is a list of characters enclosed by [ and ].  It
       matches any single character in that list.  If the first  character  of
       the  list is the caret ^ then it matches any character not in the list;
       it is unspecified whether it matches an encoding error.   For  example,
       the regular expression [0123456789] matches any single digit.

       Within  a  bracket  expression,  a  range  expression  consists  of two
       characters separated by a hyphen.  It matches any single character that
       sorts  between  the  two  characters,  inclusive,  using  the  locale's
       collating  sequence  and  character set.  For example, in the default C
       locale, [a-d] is equivalent to [abcd].  Many locales sort characters in
       dictionary  order,  and  in  these  locales  [a-d]  is  typically   not
       equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example.
       To  obtain  the  traditional interpretation of bracket expressions, you
       can use the C locale by setting the LC_ALL environment variable to  the
       value C.

       Finally,  certain  named  classes  of  characters are predefined within
       bracket expressions, as follows.  Their names are self explanatory, and
       they  are  [:alnum:],  [:alpha:],  [:blank:],   [:cntrl:],   [:digit:],
       [:graph:],  [:lower:],  [:print:], [:punct:], [:space:], [:upper:], and
       [:xdigit:].  For example, [[:alnum:]]  means  the  character  class  of
       numbers  and  letters in the current locale.  In the C locale and ASCII
       character set encoding, this is the same as  [0-9A-Za-z].   (Note  that
       the  brackets  in these class names are part of the symbolic names, and
       must be included in addition to the  brackets  delimiting  the  bracket
       expression.)   Most  meta-characters  lose their special meaning inside
       bracket expressions.  To include a literal ]  place  it  first  in  the
       list.   Similarly,  to include a literal ^ place it anywhere but first.
       Finally, to include a literal - place it last.

   Anchoring
       The caret ^ and the dollar sign $ are meta-characters that respectively
       match the empty string at the beginning and end of a line.

   The Backslash Character and Special Expressions
       The symbols \< and \>  respectively  match  the  empty  string  at  the
       beginning and end of a word.  The symbol \b matches the empty string at
       the  edge  of a word, and \B matches the empty string provided it's not
       at the edge of a word.  The symbol \w is a synonym for [_[:alnum:]] and
       \W is a synonym for [^_[:alnum:]].

   Repetition
       A regular expression may be  followed  by  one  of  several  repetition
       operators:
       ?      The preceding item is optional and matched at most once.
       *      The preceding item will be matched zero or more times.
       +      The preceding item will be matched one or more times.
       {n}    The preceding item is matched exactly n times.
       {n,}   The preceding item is matched n or more times.
       {,m}   The  preceding  item  is matched at most m times.  This is a GNU
              extension.
       {n,m}  The preceding item is matched at least n  times,  but  not  more
              than m times.

   Concatenation
       Two  regular  expressions  may  be  concatenated; the resulting regular
       expression matches any string formed by  concatenating  two  substrings
       that respectively match the concatenated expressions.

   Alternation
       Two  regular  expressions  may  be  joined by the infix operator |; the
       resulting  regular  expression  matches  any  string  matching   either
       alternate expression.

   Precedence
       Repetition  takes  precedence  over  concatenation, which in turn takes
       precedence over alternation.  A whole expression  may  be  enclosed  in
       parentheses   to   override   these   precedence   rules   and  form  a
       subexpression.

   Back-references and Subexpressions
       The back-reference \n, where n is a single digit, matches the substring
       previously matched  by  the  nth  parenthesized  subexpression  of  the
       regular expression.

   Basic vs Extended Regular Expressions
       In  basic  regular expressions the meta-characters ?, +, {, |, (, and )
       lose their special meaning; instead use the  backslashed  versions  \?,
       \+, \{, \|, \(, and \).

EXIT STATUS
       Normally the exit status is 0 if a line is selected, 1 if no lines were
       selected, and 2 if an error occurred.  However, if the -q or --quiet or
       --silent  is  used and a line is selected, the exit status is 0 even if
       an error occurred.

ENVIRONMENT
       The  behavior  of  grep  is  affected  by  the  following   environment
       variables.

       The  locale  for  category  LC_foo  is specified by examining the three
       environment variables LC_ALL, LC_foo, LANG, in that order.   The  first
       of  these  variables that is set specifies the locale.  For example, if
       LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the  Brazilian
       Portuguese  locale  is used for the LC_MESSAGES category.  The C locale
       is used if none of these environment variables are set, if  the  locale
       catalog  is  not  installed,  or if grep was not compiled with national
       language support (NLS).  The shell command locale -a lists locales that
       are currently available.

       GREP_COLORS
              Controls how the --color option highlights output.  Its value is
              a  colon-separated  list  of  capabilities  that   defaults   to
              ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36  with  the  rv
              and ne boolean capabilities omitted  (i.e.,  false).   Supported
              capabilities are as follows.

              sl=    SGR  substring  for  whole selected lines (i.e., matching
                     lines when the -v command-line option is omitted, or non-
                     matching lines when -v is  specified).   If  however  the
                     boolean  rv capability and the -v command-line option are
                     both specified, it  applies  to  context  matching  lines
                     instead.   The  default  is  empty  (i.e., the terminal's
                     default color pair).

              cx=    SGR substring for whole context lines (i.e., non-matching
                     lines when the -v  command-line  option  is  omitted,  or
                     matching  lines  when  -v  is specified).  If however the
                     boolean rv capability and the -v command-line option  are
                     both specified, it applies to selected non-matching lines
                     instead.   The  default  is  empty  (i.e., the terminal's
                     default color pair).

              rv     Boolean value that reverses (swaps) the meanings  of  the
                     sl=  and cx= capabilities when the -v command-line option
                     is specified.  The default is false (i.e., the capability
                     is omitted).

              mt=01;31
                     SGR substring for matching non-empty text in any matching
                     line (i.e., a selected  line  when  the  -v  command-line
                     option   is  omitted,  or  a  context  line  when  -v  is
                     specified).  Setting this is equivalent to  setting  both
                     ms=  and mc= at once to the same value.  The default is a
                     bold  red  text  foreground   over   the   current   line
                     background.

              ms=01;31
                     SGR  substring  for matching non-empty text in a selected
                     line.  (This is only used when the -v command-line option
                     is omitted.)  The effect  of  the  sl=  (or  cx=  if  rv)
                     capability  remains  active  when  this  kicks  in.   The
                     default is a bold red text foreground  over  the  current
                     line background.

              mc=01;31
                     SGR  substring  for  matching non-empty text in a context
                     line.  (This is only used when the -v command-line option
                     is specified.)  The effect of the  cx=  (or  sl=  if  rv)
                     capability  remains  active  when  this  kicks  in.   The
                     default is a bold red text foreground  over  the  current
                     line background.

              fn=35  SGR  substring for file names prefixing any content line.
                     The  default  is  a  magenta  text  foreground  over  the
                     terminal's default background.

              ln=32  SGR  substring  for  line  numbers  prefixing any content
                     line.  The default is a green text  foreground  over  the
                     terminal's default background.

              bn=32  SGR  substring  for  byte  offsets  prefixing any content
                     line.  The default is a green text  foreground  over  the
                     terminal's default background.

              se=36  SGR  substring  for  separators that are inserted between
                     selected line fields (:), between  context  line  fields,
                     (-),  and  between  groups of adjacent lines when nonzero
                     context is specified (--).  The default is  a  cyan  text
                     foreground over the terminal's default background.

              ne     Boolean  value  that prevents clearing to the end of line
                     using Erase in Line (EL) to Right  (\33[K)  each  time  a
                     colorized  item  ends.   This  is  needed on terminals on
                     which EL is not supported.  It  is  otherwise  useful  on
                     terminals  for  which  the back_color_erase (bce) boolean
                     terminfo capability  does  not  apply,  when  the  chosen
                     highlight colors do not affect the background, or when EL
                     is  too  slow or causes too much flicker.  The default is
                     false (i.e., the capability is omitted).

              Note that boolean capabilities have  no  =...  part.   They  are
              omitted (i.e., false) by default and become true when specified.

              See   the   Select   Graphic  Rendition  (SGR)  section  in  the
              documentation of the text terminal that is  used  for  permitted
              values   and  their  meaning  as  character  attributes.   These
              substring values are integers in decimal representation and  can
              be  concatenated with semicolons.  grep takes care of assembling
              the result into a  complete  SGR  sequence  (\33[...m).   Common
              values to concatenate include 1 for bold, 4 for underline, 5 for
              blink,  7 for inverse, 39 for default foreground color, 30 to 37
              for foreground colors, 90 to 97  for  16-color  mode  foreground
              colors,  38;5;0  to  38;5;255  for  88-color and 256-color modes
              foreground colors, 49 for default background color, 40 to 47 for
              background colors, 100  to  107  for  16-color  mode  background
              colors,  and 48;5;0 to 48;5;255 for 88-color and 256-color modes
              background colors.

       LC_ALL, LC_COLLATE, LANG
              These variables specify the locale for the LC_COLLATE  category,
              which  determines the collating sequence used to interpret range
              expressions like [a-z].

       LC_ALL, LC_CTYPE, LANG
              These variables specify the locale for  the  LC_CTYPE  category,
              which  determines the type of characters, e.g., which characters
              are whitespace.  This category  also  determines  the  character
              encoding,  that  is, whether text is encoded in UTF-8, ASCII, or
              some other encoding.  In the C or POSIX locale,  all  characters
              are  encoded  as  a  single  byte  and  every  byte  is  a valid
              character.

       LC_ALL, LC_MESSAGES, LANG
              These variables specify the locale for the LC_MESSAGES category,
              which determines the language that grep uses for messages.   The
              default C locale uses American English messages.

       POSIXLY_CORRECT
              If  set, grep behaves as POSIX requires; otherwise, grep behaves
              more like other GNU programs.  POSIX requires that options  that
              follow  file  names  must  be treated as file names; by default,
              such options are permuted to the front of the operand  list  and
              are  treated as options.  Also, POSIX requires that unrecognized
              options be diagnosed as “illegal”, but since they are not really
              against the law the default is to diagnose them as “invalid”.

NOTES
       This man page is maintained only fitfully; the  full  documentation  is
       often more up-to-date.

COPYRIGHT
       Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc.

       This is free software; see the source for copying conditions.  There is
       NO  warranty;  not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
       PURPOSE.

BUGS
   Reporting Bugs
       Email bug reports to the bug-reporting address ⟨bug-grep@gnu.org⟩.   An
       email  archive  ⟨https://lists.gnu.org/mailman/listinfo/bug-grep⟩ and a
       bug  tracker   ⟨https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep
       are available.

   Known Bugs
       Large  repetition  counts  in the {n,m} construct may cause grep to use
       lots of memory.  In addition, certain other obscure regular expressions
       require exponential time and space, and may cause grep to  run  out  of
       memory.

       Back-references are very slow, and may require exponential time.

EXAMPLE
       The  following  example  outputs  the location and contents of any line
       containing “f” and ending in “.c”, within all files in the current  di‐
       rectory whose names contain “g” and end in “.h”.  The -n option outputs
       line  numbers,  the  --  argument treats expansions of “*g*.h” starting
       with “-” as file names not options, and the empty file /dev/null causes
       file names to be output even if only one file name happens to be of the
       form “*g*.h”.

         $ grep -n -- 'f.*\.c$' *g*.h /dev/null
         argmatch.h:1:/* definitions and prototypes for argmatch.c

       The only line that matches is line 1 of argmatch.h.  Note that the reg‐
       ular expression syntax used in the pattern differs  from  the  globbing
       syntax that the shell uses to match file names.

SEE ALSO
   Regular Manual Pages
       awk(1),  cmp(1),  diff(1), find(1), perl(1), sed(1), sort(1), xargs(1),
       read(2),  pcre2(3),   pcre2syntax(3),   pcre2pattern(3),   terminfo(5),
       glob(7), regex(7)

   Full Documentation
       A complete manual ⟨https://www.gnu.org/software/grep/manual/⟩ is avail‐
       able.   If  the  info  and grep programs are properly installed at your
       site, the command

              info grep

       should give you access to the complete manual.

GNU grep 3.11                     2019-12-29                           GREP(1)

man grep 번역기 번역본

더보기

GREP(1)      사용자 명령              GREP(1)

이름
grep, egrep, fgrep, rgrep - 패턴과 일치하는 줄을 출력

요약
grep [옵션...] PATTERNS [파일...]
grep [옵션...] -e PATTERNS ... [파일...]
grep [옵션...] -f PATTERN_FILE ... [파일...]

설명
grep은 각 FILE에서 PATTERNS를 검색합니다. PATTERNS는 줄바꿈 문자로 구분된 하나 이상의
패턴이며 grep은 패턴과 일치하는 각 줄을
출력합니다. 일반적으로 grep이 셸 명령에서 사용될 때 PATTERNS는 따옴표로 묶어야 합니다.

"-"의 FILE은 표준 입력을 의미합니다. FILE이 주어지지 않으면
재귀 검색은 작업 디렉토리를 검사하고 비재귀 검색은 표준 입력을 읽습니다.

Debian에는 변형 프로그램 egrep, fgrep 및 rgrep도 포함되어 있습니다.
이러한 프로그램은 각각 grep -E, grep -F 및 grep -r과 동일합니다. 이러한 변형은 업스트림에서 더 이상 사용되지 않지만 Debian은 이전 버전과의 호환성을 제공합니다. 이식성을 위해 변형 프로그램을 피하고 대신 grep을 관련 옵션과 함께 사용하는 것이 좋습니다.

옵션
일반 프로그램 정보
--help 사용법 메시지를 출력하고 종료합니다.

-V, --version
grep의 버전 번호를 출력하고 종료합니다.

패턴 구문
-E, --extended-regexp
PATTERNS를 확장된 정규 표현식(ERE, 아래 참조)으로 해석합니다.

-F, --fixed-strings
PATTERNS를 정규 표현식이 아닌 고정 문자열로 해석합니다.

-G, --basic-regexp
PATTERNS를 기본 정규 표현식(BRE, 아래 참조)으로 해석합니다. 이것이 기본값입니다.

-P, --perl-regexp
PATTERNS를 Perl 호환 정규 표현식(PCRE)으로 해석합니다. 이 옵션은 -z
(--null-data) 옵션과 결합하면 실험적이며 grep -P는 구현되지 않은 기능에 대해 경고할 수 있습니다.

일치 제어
-e PATTERNS, --regexp=PATTERNS
PATTERNS를 패턴으로 사용합니다. 이 옵션을 여러 번 사용하거나 -f (--file) 옵션과 결합하면 제공된 모든
패턴을 검색합니다. 이 옵션은 “-”로 시작하는 패턴을 보호하는 데 사용할 수 있습니다.

-f FILE, --file=FILE
줄당 하나씩 FILE에서 패턴을 가져옵니다. 이 옵션을 여러 번 사용하거나 -e (--regexp) 옵션과 결합하면 제공된 모든
패턴을 검색합니다. 빈 파일에는 패턴이 하나도 없으므로 아무것도 일치하지 않습니다. FILE이 -이면 표준 입력에서 패턴을 읽습니다.

-i, --ignore-case
패턴과 입력 데이터에서 대소문자 구분을 무시하여
대소문자만 다른 문자가 서로 일치하도록 합니다.

--no-ignore-case
패턴과 입력 데이터에서 대소문자 구분을 무시하지 않습니다.
이것이 기본값입니다. 이 옵션은 -i를 이미 사용하는 셸 스크립트에 전달하여 두 옵션이 서로를 무시하기 때문에 효과를 취소하는 데 유용합니다.

-v, --invert-match
일치하지 않는 줄을 선택하기 위해 일치의 의미를 반전합니다.

-w, --word-regexp
전체 단어를 구성하는 일치가 포함된 줄만 선택합니다. 테스트는 일치하는 하위 문자열이
줄의 시작 부분에 있거나
단어가 아닌 구성 문자가 앞에 와야 한다는 것입니다. 마찬가지로 줄의 끝에 있거나
단어가 아닌 구성 문자가 뒤에 와야 합니다.
단어 구성 문자는 문자, 숫자 및
밑줄입니다. -x도 지정된 경우 이 옵션은 효과가 없습니다.

-x, --line-regexp
전체 줄과 정확히 일치하는 일치 항목만 선택합니다.
정규 표현식 패턴의 경우 패턴을 괄호로 묶은 다음
^와 $로 둘러싼 것과 같습니다.


일반 출력 제어
-c, --count
일반 출력을 억제합니다. 대신 각 입력 파일에 대해 일치하는 줄의 수를 인쇄합니다. -v, --invert-match 옵션(위 참조)을 사용하여 일치하지 않는 줄을 계산합니다.

--color[=WHEN], --colour[=WHEN]
일치하는(비어 있지 않은) 문자열, 일치하는 줄,
컨텍스트 줄, 파일 이름, 줄 번호, 바이트 오프셋 및
구분 기호(필드 및 컨텍스트 줄 그룹)를 이스케이프 시퀀스로 둘러싸서 터미널에 색상으로 표시합니다. 색상은
환경 변수 GREP_COLORS에 의해 정의됩니다. WHEN은
never, always 또는 auto입니다.

-L, --files-without-match
일반 출력을 억제합니다. 대신 각 입력 파일의 이름을 인쇄합니다. 이 입력 파일에서 일반적으로 출력이 인쇄되지 않았을 것입니다.

-l, --files-with-matches
일반 출력을 억제합니다. 대신 각 입력 파일의 이름을 인쇄합니다. 이 입력 파일에서 일반적으로 출력이 인쇄되었을 것입니다.
각 입력 파일 스캔은 첫 번째 일치 시 중지됩니다.

-m NUM, --max-count=NUM
NUM개의 일치하는 줄 이후에 파일 읽기를 중지합니다. NUM이 0이면
grep은 입력을 읽지 않고 바로 중지합니다. -1의 NUM은
무한대로 처리되고 grep은 중지되지 않습니다. 이것이 기본값입니다.
입력이 일반 파일의 표준 입력이고 NUM개의 일치하는 줄이 출력되면 grep은 종료하기 전에 표준 입력이
마지막 일치하는 줄 바로 뒤에 위치하도록 합니다.
후행 컨텍스트 줄이 있는지 여부와 관계없이.
이를 통해 호출 프로세스가 검색을 재개할 수 있습니다. grep이
NUM개의 일치하는 줄 이후에 중지되면 후행 컨텍스트 줄을 출력합니다. -c 또는 --count 옵션도 사용하는 경우 grep은
NUM개보다 큰 개수를 출력하지 않습니다. -v 또는
--invert-match 옵션도 사용하는 경우 grep은 NUM개의 일치하지 않는 줄을 출력한 후에 중지합니다.

-o, --only-matching
일치하는 줄의 일치된(비어 있지 않은) 부분만 인쇄합니다.
각 부분은 별도의 출력 줄에 있습니다.

-q, --quiet, --silent
조용합니다. 표준 출력에 아무것도 쓰지 않습니다. 일치 항목이 발견되면
오류가 감지된 경우에도 0 상태로 즉시 종료합니다. -s 또는 --no-messages 옵션도 참조하세요.

-s, --no-messages
존재하지 않거나 읽을 수 없는 파일에 대한 오류 메시지를 억제합니다.

출력 줄 접두사 제어
-b, --byte-offset
각 출력 줄 앞에 입력 파일 내에서 0부터 시작하는 바이트 오프셋을 인쇄합니다. -o(--only-matching)가 지정된 경우 일치하는 부분 자체의 오프셋을 인쇄합니다.

-H, --with-filename
각 일치 항목에 대한 파일 이름을 인쇄합니다. 검색할 파일이 두 개 이상인 경우 기본값입니다. GNU 확장 기능입니다.

-h, --no-filename
출력 시 파일 이름 접두사를 억제합니다. 검색할 파일이 하나(또는 표준 입력만)인 경우 기본값입니다.

--label=LABEL
실제로 표준 입력에서 나오는 입력을 파일 LABEL에서 나오는 입력으로 표시합니다. 이것은 검색하기 전에 파일의 내용을 변환하는 명령에 유용할 수 있습니다. 예: gzip -cd
foo.gz | grep --label=foo -H 'some pattern'. -H
옵션도 참조하세요.

-n, --line-number
각 출력 줄에 입력 파일 내에서 1부터 시작하는 줄 번호를 접두사로 붙입니다.

-T, --initial-tab
실제 줄 내용의 첫 번째 문자가 탭 정지에 있어야 탭 정렬이 정상적으로 보입니다.
이 옵션은 실제 내용에 출력을 접두사로 붙이는 옵션인 -H,-n 및 -b와 함께 유용합니다. 단일 파일의 줄이 모두 같은 열에서 시작할 가능성을 높이기 위해
줄 번호와 바이트 오프셋(있는 경우)도 최소 크기 필드 너비로 인쇄됩니다.

-Z, --null
일반적으로 파일 이름 뒤에 오는 문자 대신 0바이트(ASCII NUL 문자)를 출력합니다.
예를 들어 grep
-lZ는 일반적인 줄 바꿈 대신 각 파일 이름 뒤에 0바이트를 출력합니다.
이 옵션을 사용하면 줄 바꿈과 같은 특이한 문자가 포함된 파일 이름이 있는 경우에도 출력이 모호하지 않습니다. 이 옵션은 find
-print0, perl -0, sort -z, xargs -0과 같은 명령과 함께 사용하여 줄바꿈 문자가 포함된 임의의
파일 이름을 처리할 수 있습니다.



컨텍스트 줄 제어
-A NUM, --after-context=NUM
일치하는 줄 뒤에 NUM 줄의 후행 컨텍스트를 인쇄합니다.
연속된 일치 그룹 사이에 그룹 구분 기호(--)가 포함된 줄을 넣습니다. -o 또는 --only-matching
옵션을 사용하면 효과가 없고 경고가 표시됩니다.

-B NUM, --before-context=NUM
일치하는 줄 앞에 NUM 줄의 선행 컨텍스트를 인쇄합니다.
연속된 일치 그룹 사이에 그룹 구분 기호(--)가 포함된 줄을 넣습니다. -o 또는 --only-matching
옵션을 사용하면 효과가 없고 경고가 표시됩니다.

-C NUM, -NUM, --context=NUM
출력 컨텍스트의 NUM 줄을 인쇄합니다. 연속된 일치 그룹 사이에
그룹 구분 기호(--)가 포함된 줄을 넣습니다. -o 또는 --only-matching
옵션을 사용하면 효과가 없고 경고가 표시됩니다.

--group-separator=SEP
-A, -B 또는 -C가 사용 중일 때는 줄 그룹 사이에 -- 대신 SEP를 인쇄합니다.

--no-group-separator
-A, -B 또는 -C가 사용 중일 때는 줄 그룹 사이에 구분 기호를 인쇄하지 않습니다.


파일 및 디렉토리 선택
-a, --text
이진 파일을 텍스트인 것처럼 처리합니다. 이는 --binary-files=text 옵션과 동일합니다.

--binary-files=TYPE
파일의 데이터 또는 메타데이터가 파일에 이진 데이터가 포함되어 있음을 나타내는 경우 해당 파일이 TYPE 유형이라고 가정합니다. 텍스트가 아닌
바이트는 이진 데이터를 나타냅니다. 이는 현재 로케일에 대해 잘못 인코딩된 출력 바이트이거나 -z 옵션이 제공되지 않은 경우 null 입력
바이트입니다.

기본적으로 TYPE은 이진이고 grep은 null 입력 이진 데이터가 발견된 후 출력을 억제하고 잘못 인코딩된 데이터가 포함된 출력
줄을 억제합니다. 일부 출력이 억제되면 grep은 표준 오류에 대한 메시지를 출력 뒤에 표시하여 이진 파일이 일치한다는 메시지를 표시합니다.

TYPE이 without-match인 경우 grep이 null 입력 이진
데이터를 발견하면 나머지 파일이 일치하지 않는다고 가정합니다. 이는 -I 옵션과 동일합니다.

TYPE이 텍스트인 경우 grep은 바이너리 파일을 마치 텍스트인 것처럼 처리합니다. 이는 -a 옵션과 동일합니다.

type이 바이너리인 경우 grep은 -z 옵션 없이도 텍스트가 아닌 바이트를 줄
종결자로 처리할 수 있습니다. 즉,
바이너리 대 텍스트를 선택하면 패턴이 파일과 일치하는지 여부에 영향을 미칠 수 있습니다.
예를 들어, type이 바이너리인 경우 패턴 q$는 q와 일치할 수 있으며
바로 뒤에 null 바이트가 올 수 있지만 type이 텍스트인 경우 일치하지 않습니다.
반대로 type이 바이너리인 경우
패턴 . (마침표)는 null 바이트와 일치하지 않을 수 있습니다.

경고: -a 옵션은 바이너리 가비지를 출력할 수 있으며, 이는 출력이 터미널이고
터미널 드라이버가 일부를 명령으로 해석하는 경우 불쾌한 부작용을 일으킬 수 있습니다.
반면, 텍스트 인코딩이 알려지지 않은 파일을 읽을 때는 -a를 사용하거나
환경에서 LC_ALL='C'를 설정하는 것이 도움이 될 수 있습니다. 일치 항목이 직접 표시하기에 안전하지 않더라도 더 많은 일치 항목을 찾을 수 있습니다.

-D ACTION, --devices=ACTION
입력 파일이 장치, FIFO 또는 소켓인 경우 ACTION을 사용하여 처리합니다. 기본적으로 ACTION은 읽기입니다. 즉, 장치가 일반 파일인 것처럼 읽힙니다. ACTION이 건너뛰기인 경우 장치가 자동으로 건너뜁니다.

-d ACTION, --directories=ACTION
입력 파일이 디렉토리인 경우 ACTION을 사용하여 처리합니다. 기본적으로 ACTION은 읽기입니다. 즉, 디렉토리가 일반 파일인 것처럼 읽힙니다. ACTION이 건너뛰기인 경우 디렉토리를 자동으로 건너뜁니다. ACTION이 재귀인 경우 각 디렉토리 아래의 모든 파일을 재귀적으로 읽습니다. 명령줄에 있는 경우에만 심볼릭 링크를 따릅니다. 이는 -r 옵션과 동일합니다.

--exclude=GLOB
와일드카드 매칭을 사용하여
패턴 GLOB와 일치하는 이름 접미사가 있는 명령줄 파일을 건너뜁니다. 이름 접미사는
전체 이름 또는 이름에서 슬래시(/) 바로 뒤에 슬래시가 아닌 문자로 시작하는 끝 부분입니다.
재귀적으로 검색할 때 기본 이름이
GLOB와 일치하는 모든 하위 파일을 건너뜁니다. 기본 이름은 마지막 슬래시 뒤의 부분입니다. 패턴은
*, ?, [...]를 와일드카드로 사용할 수 있으며 \를 사용하여 와일드카드 또는
백슬래시 문자를 그대로 인용할 수 있습니다.

--exclude-from=FILE
기본 이름이 FILE에서 읽은 모든 파일 이름 glob와 일치하는 파일을 건너뜁니다(
--exclude에서 설명한 대로 와일드카드 매칭을 사용).

--exclude-dir=GLOB
패턴 GLOB와 일치하는 이름 접미사가 있는 모든 명령줄 디렉토리를 건너뜁니다.
재귀적으로 검색할 때 기본 이름이 GLOB와 일치하는 모든 하위 디렉토리를 건너뜁니다. GLOB에서 중복된
끝 슬래시를 무시합니다.

-I 일치하는 데이터가 없는 것처럼 바이너리 파일을 처리합니다.
이는 --binary-files=without-match 옵션과 동일합니다.

--include=GLOB
--exclude에서 설명한 대로 와일드카드
일치를 사용하여 기본 이름이 GLOB와 일치하는 파일만 검색합니다. 모순되는
--include 및 --exclude 옵션이 지정된 경우 마지막으로 일치하는 옵션이
이깁니다. --include 또는 --exclude 옵션이 일치하지 않으면 첫 번째 옵션이 --include가 아닌 한 파일이 포함됩니다.

-r, --recursive
명령줄에 있는 경우에만 심볼릭 링크에 따라 각 디렉토리 아래의 모든 파일을 재귀적으로 읽습니다.
파일 피연산자가 지정되지 않은 경우 grep은 작업 디렉토리를 검색합니다.
이는 -d recurse 옵션과 동일합니다.

-R, --dereference-recursive
각 디렉토리 아래의 모든 파일을 재귀적으로 읽습니다. -r과 달리 모든 심볼릭 링크를 따릅니다.

기타 옵션
--line-buffered
출력에 줄 버퍼링을 사용합니다. 이로 인해 성능이 저하될 수 있습니다.

-U, --binary
파일을 바이너리로 처리합니다. 기본적으로 MS-DOS 및 MS-
Windows에서 grep은 --binary-files 옵션에 설명된 대로 파일이 텍스트인지 바이너리인지 추측합니다. grep이
파일이 텍스트 파일이라고 판단하면 원래 파일 내용에서 CR 문자를 제거합니다(^ 및 $가 있는 정규 표현식이 제대로 작동하도록
하기 위함). -U를 지정하면 이러한 추측이 무시되어 모든 파일이 읽혀지고 일치하는 메커니즘에 그대로 전달됩니다. 파일이 각 줄 끝에 CR/LF 쌍이 있는 텍스트 파일인 경우 일부 정규 표현식이 실패합니다. 이 옵션은 MS-DOS 및 MS-Windows 이외의 플랫폼에는 효과가 없습니다.

-z, --null-data
입력 및 출력 데이터를 줄의 시퀀스로 처리하며, 각 줄은 줄바꿈 문자 대신 0바이트(ASCII NUL 문자)로 끝납니다. -Z 또는 --null 옵션과 마찬가지로 이 옵션은 sort -z와 같은 명령과 함께 사용하여 임의의 파일 이름을 처리할 수 있습니다.

정규 표현식
정규 표현식은 문자열 집합을 설명하는 패턴입니다.
정규 표현식은 다양한 연산자를 사용하여 더 작은 표현식을 결합하는 산술 표현식과 유사하게 구성됩니다.

grep은 세 가지 다른 버전의 정규 표현식 구문을 이해합니다.
"기본"(BRE), "확장"(ERE) 및 "perl"(PCRE). GNU grep에서 기본
및 확장 정규 표현식은 동일한 패턴 매칭 기능에 대한 다른 표기법일 뿐입니다. 다른 구현에서 기본
정규 표현식은 일반적으로 확장보다 덜 강력하지만
가끔은 그 반대입니다. 다음 설명은 확장 정규 표현식에 적용됩니다. 기본 정규 표현식의 차이점은 나중에 요약합니다. Perl 호환 정규 표현식은 기능이 다르며 pcre2syntax(3) 및 pcre2pattern(3)에 설명되어 있지만 PCRE 지원이 활성화된 경우에만 작동합니다.

기본 구성 요소는 단일 문자와 일치하는 정규 표현식입니다. 모든 문자와 숫자를 포함한 대부분의 문자는
자체와 일치하는 정규 표현식입니다. 특별한 의미가 있는 모든 메타 문자는
백슬래시로 앞에 인용할 수 있습니다.

마침표 .는 단일 문자와 일치합니다. 인코딩 오류와 일치하는지 여부는 지정되지 않습니다.

문자 클래스와 대괄호 표현식
대괄호 표현식은 [ 및 ]로 묶인 문자 목록입니다.
해당 목록의 모든 단일 문자와 일치합니다. 목록의 첫 번째 문자가 캐럿 ^인 경우 목록에 없는 모든 문자와 일치합니다.
인코딩 오류와 일치하는지 여부는 지정되지 않습니다. 예를 들어,
정규 표현식 [0123456789]는 모든 단일 숫자와 일치합니다.

대괄호 표현식 내에서 범위 표현식은 하이픈으로 구분된 두 개의
문자로 구성됩니다.
로케일의 정렬 순서와 문자 집합을 사용하여 두 문자 사이를 정렬하는 모든 단일 문자와 일치합니다. 예를 들어, 기본 C
로케일에서 [a-d]는 [abcd]와 동일합니다. 많은 로케일이 문자를
사전 순서로 정렬하고 이러한 로케일에서 [a-d]는 일반적으로
[abcd]와 동일하지 않습니다. 예를 들어 [aBbCcDd]와 동일할 수 있습니다.
대괄호 표현식의 기존 해석을 얻으려면 LC_ALL 환경 변수를 값 C로 설정하여 C 로케일을 사용할 수 있습니다.

마지막으로, 다음과 같이 대괄호 표현식 내에 특정 명명된 문자 클래스가 미리 정의되어 있습니다. 이름은 자체 설명이 가능하며, [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:],
[:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], 및
[:xdigit:]입니다. 예를 들어, [[:alnum:]]은 현재 로케일의 숫자와 문자의 문자 클래스를 의미합니다. C 로케일 및 ASCII
문자 세트 인코딩에서 이는 [0-9A-Za-z]와 동일합니다. (참고로
이 클래스 이름의 대괄호는 기호 이름의 일부이며,
대괄호 표현식을 구분하는 대괄호 외에도 포함되어야 합니다.) 대부분의 메타 문자는
대괄호 표현식 내에서 특별한 의미를 잃습니다. 리터럴 ]를 포함하려면
목록의 처음에 배치합니다. 마찬가지로 리터럴 ^를 포함하려면 처음이 아닌 다른 곳에 배치합니다.
마지막으로 리터럴 -를 포함하려면 마지막에 배치합니다.

앵커링
캐럿 ^와 달러 기호 $는 각각
줄의 시작과 끝에 있는 빈 문자열과 일치하는 메타 문자입니다.

백슬래시 문자와 특수 표현식
기호 \<와 \>는 각각
단어의 시작과 끝에 있는 빈 문자열과 일치합니다. 기호 \b는
단어의 가장자리에 있는 빈 문자열과 일치하고, \B는
단어의 가장자리에 있지 않은 경우 빈 문자열과 일치합니다. 기호 \w는 [_[:alnum:]]의 동의어이고
\W는 [^_[:alnum:]]의 동의어입니다.

반복
정규 표현식 뒤에는 여러 반복
연산자 중 하나가 올 수 있습니다.
? 이전 항목은 선택 사항이며 최대 한 번만 일치합니다.
* 이전 항목은 0회 이상 일치합니다.
+ 이전 항목은 1회 이상 일치합니다.
{n} 이전 항목은 정확히 n회 일치합니다.
{n,} 이전 항목은 n회 이상 일치합니다.
{,m} 이전 항목은 최대 m회 일치합니다. 이것은 GNU
확장입니다.
{n,m} 이전 항목은 최소 n회 일치하지만 최대 m회
일치합니다.


연결
두 개의 정규 표현식을 연결할 수 있습니다. 결과 정규 표현식은 연결된 표현식과 각각 일치하는 두 개의 하위 문자열을 연결하여 형성된 모든 문자열과 일치합니다.

대체
두 개의 정규 표현식은 중위 연산자 |로 연결할 수 있습니다. 결과 정규 표현식은 두 개의 대체 표현식과 일치하는 모든 문자열과 일치합니다.

우선순위
반복은 연결보다 우선하며, 연결은 대체보다 우선합니다. 전체 표현식을 괄호로 묶어 이러한 우선순위 규칙을 무시하고 하위 표현식을 형성할 수 있습니다.

역참조 및 하위 표현식
역참조 \n(여기서 n은 단일 숫자)은 정규 표현식의 n번째 괄호로 묶인 하위 표현식과 이전에 일치한 하위 문자열과 일치합니다.

기본 대 확장 정규 표현식
기본 정규 표현식에서 메타 문자 ?, +, {, |, (, 및 )는 특별한 의미를 잃습니다. 대신 백슬래시 버전 \?,
\+, \{, \|, \(, 및 \)를 사용합니다.

종료 상태
일반적으로 줄이 선택되면 종료 상태는 0이고, 줄이 선택되지 않으면 1이며
오류가 발생하면 2입니다. 그러나 -q 또는 --quiet 또는
--silent를 사용하고 줄이 선택되면 오류가 발생하더라도 종료 상태는 0입니다.

환경
grep의 동작은 다음 환경
변수의 영향을 받습니다.

범주 LC_foo의 로캘은 세 가지
환경 변수 LC_ALL, LC_foo, LANG을 순서대로 검사하여 지정합니다. 설정된 이러한 변수 중 첫 번째 변수는 로캘을 지정합니다. 예를 들어
LC_ALL이 설정되지 않았지만 LC_MESSAGES가 pt_BR로 설정된 경우 LC_MESSAGES 범주에 브라질
포르투갈어 로캘이 사용됩니다. C 로케일은 이러한 환경 변수가 설정되지 않은 경우, 로케일 카탈로그가 설치되지 않은 경우 또는 grep이 국가 언어 지원(NLS)으로 컴파일되지 않은 경우 사용됩니다. 셸 명령인 locale -a는 현재 사용 가능한 로케일을 나열합니다.


GREP_COLORS
--color 옵션이 출력을 강조하는 방식을 제어합니다. 값은
콜론으로 구분된 기능 목록이며, 기본값은
ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36이며 rv
및 ne 부울 기능은 생략됩니다(즉, false). 지원되는
기능은 다음과 같습니다.

sl= 선택한 줄 전체에 대한 SGR 하위 문자열(즉, -v 명령줄 옵션이 생략된 경우 일치하는 줄 또는 -v가 지정된 경우 일치하지 않는 줄). 그러나
부울 rv 기능과 -v 명령줄 옵션이 모두
지정된 경우 컨텍스트가 일치하는 줄에 적용됩니다. 기본값은 비어 있습니다(즉, 터미널의
기본 색상 쌍).

cx= SGR 전체 컨텍스트 줄에 대한 하위 문자열(즉, -v 명령줄 옵션이 생략된 경우 일치하지 않는 줄 또는 -v가 지정된 경우 일치하는 줄). 그러나
boolean rv 기능과 -v 명령줄 옵션이 모두 지정된 경우
선택한 일치하지 않는 줄에 적용됩니다. 기본값은 비어 있습니다(즉, 터미널의
기본 색상 쌍).

rv -v 명령줄 옵션이 지정된 경우
sl= 및 cx= 기능의 의미를 반전(스왑)하는 부울 값입니다. 기본값은 false입니다(즉, 기능이
생략됨).

mt=01;31
일치하는 모든 줄에서 비어 있지 않은 텍스트와 일치하는 SGR 하위 문자열(즉, -v 명령줄 옵션이 생략된 경우 선택한 줄 또는 -v가
지정된 경우 컨텍스트 줄). 이 값을 설정하는 것은
ms=와 mc=를 한 번에 같은 값으로 설정하는 것과 같습니다. 기본값은
현재 줄 배경 위에 굵은 빨간색 텍스트 전경입니다.

ms=01;31
선택된 줄에서 비어 있지 않은 텍스트와 일치하기 위한 SGR 하위 문자열입니다.
(이것은 -v 명령줄 옵션이 생략된 경우에만 사용됩니다.) sl= (또는 rv인 경우 cx=) 기능의 효과는 이것이 작동할 때 활성 상태로 유지됩니다.
기본값은
현재 줄 배경 위에 굵은 빨간색 텍스트 전경입니다.

mc=01;31
컨텍스트 줄에서 비어 있지 않은 텍스트를 일치시키기 위한 SGR 하위 문자열입니다. (이것은 -v 명령줄 옵션이 지정된 경우에만 사용됩니다.) cx=(또는 rv인 경우 sl=) 기능의 효과는 이 기능이 활성화되면 활성 상태로 유지됩니다.
기본값은 현재 줄 배경 위에 굵은 빨간색 텍스트 전경입니다.

fn=35 모든 콘텐츠 줄에 접두사를 붙인 파일 이름에 대한 SGR 하위 문자열입니다.
기본값은 터미널의 기본 배경 위에 자홍색 텍스트 전경입니다.

ln=32 모든 콘텐츠 줄에 접두사를 붙인 줄 번호에 대한 SGR 하위 문자열입니다.
기본값은 터미널의 기본 배경 위에 녹색 텍스트 전경입니다.

bn=32 모든 콘텐츠 줄에 접두사를 붙인 바이트 오프셋에 대한 SGR 하위 문자열입니다.
기본값은 터미널의 기본 배경 위에 녹색 텍스트 전경입니다.

se=36 SGR은
선택한 줄 필드(:),
컨텍스트 줄 필드(-) 및 0이 아닌
컨텍스트가 지정된 경우(--) 인접한 줄 그룹 사이에 삽입되는 구분 기호에 대한 하위 문자열입니다. 기본값은 터미널의 기본 배경 위에 시안색 텍스트
포그라운드입니다.

색상이 지정된 항목이 끝날 때마다 줄에서 지우기(EL)를 오른쪽으로(\33[K) 사용하여 줄 끝까지 지우는 것을 방지하는 ne 부울 값입니다.
EL이 지원되지 않는 터미널에서 필요합니다. 그렇지 않으면 back_color_erase(bce) 부울
terminfo 기능이 적용되지 않는 터미널에서, 선택한
강조 색상이 배경에 영향을 미치지 않는 경우 또는 EL이
너무 느리거나 너무 많이 깜빡이는 경우에 유용합니다. 기본값은
false(즉, 기능이 생략됨)입니다.

부울 기능에는 =... 부분이 없습니다. 기본적으로 생략(즉, false)되고 지정하면 true가 됩니다.

허용된 값과 문자 속성으로서의 의미에 사용되는 텍스트 터미널의
설명서에서 Select Graphic Rendition(SGR) 섹션을 참조하세요. 이러한
하위 문자열 값은 10진수 표현의 정수이며 세미콜론으로 연결할 수 있습니다. grep은 결과를 완전한 SGR 시퀀스(\33[...m)로 조립합니다. 연결할 일반적인
값으로는 굵게의 경우 1, 밑줄의 경우 4,
깜박임의 경우 5,
역색의 경우 7, ​​기본 전경색의 경우 39, 전경색의 경우 30~37, 16색 모드 전경색의 경우 90~97, 88색 및 256색 모드의 경우 38;5;0~38;5;255
전경색의 경우 38;5;0~38;5;255, 기본 배경색의 경우 49,
배경색의 경우 40~47,
16색 모드 배경색의 경우 100~107,
88색 및 256색 모드의 경우 48;5;0~48;5;255
배경색이 있습니다.

LC_ALL, LC_COLLATE, LANG
이러한 변수는 LC_COLLATE 범주의 로캘을 지정하며,
[a-z]와 같은 범위 표현식을 해석하는 데 사용되는 정렬 순서를 결정합니다.

LC_ALL, LC_CTYPE, LANG
이러한 변수는 LC_CTYPE 범주의 로캘을 지정하며,
문자의 유형, 즉 어떤 문자가 공백인지 결정합니다. 이 범주는 또한 문자 인코딩, 즉 텍스트가 UTF-8, ASCII 또는
다른 인코딩으로 인코딩되는지 여부를 결정합니다. C 또는 POSIX 로캘에서 모든 문자는
단일 바이트로 인코딩되고 모든 바이트는 유효한
문자입니다.

LC_ALL, LC_MESSAGES, LANG
이러한 변수는 LC_MESSAGES 범주의 로캘을 지정하며,
grep이 메시지에 사용하는 언어를 결정합니다.
기본 C 로캘은 미국 영어 메시지를 사용합니다.

POSIXLY_CORRECT
설정된 경우 grep은 POSIX가 요구하는 대로 동작합니다. 그렇지 않으면 grep은
다른 GNU 프로그램과 비슷하게 동작합니다. POSIX는 파일 이름 뒤에 오는 옵션은
파일 이름으로 처리해야 합니다. 기본적으로
이러한 옵션은 피연산자 목록의 앞으로 순열되고
옵션으로 처리됩니다. 또한 POSIX는 인식되지 않은
옵션을 "불법"으로 진단해야 하지만 실제로는
불법이 아니므로 기본적으로 "잘못됨"으로 진단합니다.

참고 사항
이 매뉴얼 페이지는 간헐적으로만 유지 관리됩니다. 전체 설명서는
종종 최신입니다.

저작권
저작권 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc.

이것은 무료 소프트웨어입니다. 복사 조건은 소스를 참조하세요.
보증은 없습니다. 상품성이나 특정 목적에의 적합성도 없습니다.


버그
버그 보고
버그 보고 주소 ⟨bug-grep@gnu.org⟩로 이메일 버그 보고서를 보내주세요.
이메일 보관소 ⟨https://lists.gnu.org/mailman/listinfo/bug-grep⟩ 및
버그 추적기 ⟨https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep
를 사용할 수 있습니다.

알려진 버그
{n,m} 구문에서 반복 횟수가 많으면 grep이
많은 메모리를 사용할 수 있습니다. 또한, 다른 모호한 정규 표현식은
지수 시간과 공간이 필요하고 grep이
메모리를 소진할 수 있습니다.

역참조는 매우 느리고 지수 시간이 필요할 수 있습니다.


다음 예는 현재 디렉토리의 모든 파일에서 이름이 "g"를 포함하고 ".h"로 끝나는 모든 파일 내에서 "f"를 포함하고 ".c"로 끝나는 모든 줄의 위치와 내용을 출력합니다. -n 옵션은
줄 번호를 출력하고, -- 인수는 "-"로 시작하는 "*g*.h"의 확장을
옵션이 아닌 파일 이름으로 처리하고, 빈 파일 /dev/null은
파일 이름이 하나만 "*g*.h" 형식이더라도
파일 이름을 출력합니다.

$ grep -n -- 'f.*\.c$' *g*.h /dev/null
argmatch.h:1:/* argmatch.c의 정의 및 프로토타입

일치하는 줄은 argmatch.h의 1번째 줄뿐입니다. 패턴에서 사용되는 정규 표현식 구문은 셸이 파일 이름을 일치시키는 데 사용하는 글로빙 구문과 다릅니다.

또한 참조
일반 매뉴얼 페이지
awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1),
read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5),
glob(7), regex(7)

전체 문서
전체 매뉴얼 ⟨https://www.gnu.org/software/grep/manual/⟩을 사용할 수 있습니다. info 및 grep 프로그램이 사이트에 제대로 설치되어 있으면 명령

info grep

을 사용하면 전체 매뉴얼에 액세스할 수 있습니다.

GNU grep 3.11       2019-12-29         GREP(1)

 

 

형태 : grep [옵션] [패턴] [파일]

기능 : 파일에서 패턴을 검색하여 결과를 출력한다.

 

[옵션]

-i : 대문자 소문자를 모두 검색한다.

-l : 지정한 패턴이 포함된 파일명을 출력한다.

-n : 행 번호를 출력한다.

 

grep 명령어는 혼자서 사용할 수도 있지만, 다른 명령어와 함께 쓸 때 더 편의성이 증가한다.

터미널에서는 |(shift + \) 기능으로 여러 명령어를 동시에 사용할 수 있는데

예를 들어 ls 명령어와 grep 명령어를 같이 사용하여 ls 값이 출력되는 것 중에 내가 원하는 패턴을 가진 값만 추출하는 것도 가능하다

예시) user1@user1:~$ ls -a | grep De

라고 입력할 경우 Desktop 에서 De부분이 강조되어 표기될 것이다.

 

특정 결과중 원하는 값의 일부분을 알고 있다면 | 기능으로 더욱 빠르게 알아보도록 하자.