perl: erweitertes grep

Problem

Manchmal reicht ein normaler grep nicht, um die gewünschten Ergebnisse herauszufiltern.

Lösung

Durch die Verwendung von perl können erweiterte Suchen durchgeführt werden.

Durchsuchen einer Datei nach einem Suchkriterium, stoppen, beim ersten Vorkommen einer Leerzeile ^$.

perl -ne 'exit if (/^$/); print if (/suchmuster/);' dateiname

Unter der Annahme, dass Absätze durch ein \n\n abgeschlossen sind, werden hier alle Absätze, in denen das Suchmuster vorkommt, ausgegeben.

perl -ne '$/ = "\n\n"; print if (/suchmuster/);' dateiname

Anmerkung: Sind die Absätze durch ein anderes Merkmal (z.B. abc123\n) getrennt, so kann es sinnvoll sein, in der Ausgabe eine explizite Trennzeile einzufügen.

perl -ne '$/ = "abc123\n"; print if (/suchmuster/); print "........\n" if (/suchmuster/); ' dateiname

Weiterlesen

    *      Match 0 or more times
    +      Match 1 or more times
    ?      Match 1 or 0 times
    {n}    Match exactly n times
    {n,}   Match at least n times
    {n,m}  Match at least n but not more than m times
    *?     Match 0 or more times
    +?     Match 1 or more times
    ??     Match 0 or 1 time
    {n}?   Match exactly n times
    {n,}?  Match at least n times
    {n,m}? Match at least n but not more than m times
    \t          tab                   (HT, TAB)
    \n          newline               (LF, NL)
    \r          return                (CR)
    \f          form feed             (FF)
    \a          alarm (bell)          (BEL)
    \e          escape (think troff)  (ESC)
    \033        octal char (think of a PDP-11)
    \x1B        hex char
    \c[         control char
    \l          lowercase next char (think vi)
    \u          uppercase next char (think vi)
    \L          lowercase till \E (think vi)
    \U          uppercase till \E (think vi)
    \E          end case modification (think vi)
    \Q          quote (disable) pattern metacharacters till \E
    \w  Match a "word" character (alphanumeric plus "_") (single alphanumeric character)
    \w+ Match a "word" character (more than on character)
    \W  Match a non-word character
    \s  Match a whitespace character
    \S  Match a non-whitespace character
    \d  Match a digit character
    \D  Match a non-digit character
    \b  Match a word boundary
    \B  Match a non-(word boundary)
    \A  Match only at beginning of string
    \Z  Match only at end of string, or before newline at the end
    \z  Match only at end of string
    \G  Match only where previous m//g left off (works only with /g)
 
wissen/tips_und_tricks/perl/perl-enhanced-grep.txt · Zuletzt geändert: 05.09.2010 20:31
 
Recent changes RSS feed Donate Valid XHTML 1.0 Valid CSS Recent cached RSS feed cacert-signed web site: inhalt.serviert.de