如何在Unix平台上的文件中grep标签(\t) ?


当前回答

使用echo为你插入标签grep "$(echo -e \\t)"

其他回答

下面是问Ubuntu的答案:

告诉grep使用由Perl定义的正则表达式(Perl拥有 \t as tab): grep -P "\t" <文件名称> . grep "\t" <文件名称> . grep "\t 使用文字制表符: grep "^V<tab>" <文件名> . grep "^V<tab> 使用printf打印制表符: Grep "$(printf '\t')"<文件名>

基本上有两种解决方法:

(Recommended) Use regular expression syntax supported by grep(1). Modern grep(1) supports two forms of POSIX 1003.2 regex syntax: basic (obsolete) REs, and modern REs. Syntax is described in details on re_format(7) and regex(7) man pages which are part of BSD and Linux systems respectively. The GNU grep(1) also supports Perl-compatible REs as provided by the pcre(3) library. In regex language the tab symbol is usually encoded by \t atom. The atom is supported by BSD extended regular expressions (egrep, grep -E on BSD compatible system), as well as Perl-compatible REs (pcregrep, GNU grep -P). Both basic regular expressions and Linux extended REs apparently have no support for the \t. Please consult UNIX utility man page to know which regex language it supports (hence the difference between sed(1), awk(1), and pcregrep(1) regular expressions). Therefore, on Linux: $ grep -P '\t' FILE ... On BSD alike system: $ egrep '\t' FILE ... $ grep -E '\t' FILE ... Pass the tab character into pattern. This is straightforward when you edit a script file: # no tabs for Python please! grep -q ' ' *.py && exit 1 However, when working in an interactive shell you may need to rely on shell and terminal capabilities to type the proper symbol into the line. On most terminals this can be done through Ctrl+V key combination which instructs terminal to treat the next input character literally (the V is for "verbatim"): $ grep '<Ctrl>+<V><TAB>' FILE ... Some shells may offer advanced support for command typesetting. Such, in bash(1) words of the form $'string' are treated specially: bash$ grep $'\t' FILE ... Please note though, while being nice in a command line this may produce compatibility issues when the script will be moved to another platform. Also, be careful with quotes when using the specials, please consult bash(1) for details. For Bourne shell (and not only) the same behaviour may be emulated using command substitution augmented by printf(1) to construct proper regex: $ grep "`printf '\t'`" FILE ...

您也可以使用Perl一行程序来代替grep响应。grep - p:

perl -ne 'print if /\t/' FILENAME

这对于AIX很有效。我正在搜索包含连接<\t>ACTIVE的行

voradmin cluster status | grep  JOINED$'\t'ACTIVE

 vorudb201   1       MEMBER(g) JOINED        ACTIVE
*vorucaf01   2       SECONDARY JOINED        ACTIVE

在表达式中插入制表符的另一种方法是使用Bash中不太为人所知的$'\t'引号:

grep $'foo\tbar'        # matches eg. 'foo<tab>bar'

(注意,如果你匹配固定字符串,你可以使用-F模式。)

有时使用变量可以使符号更易于阅读和管理:

tab=$'\t'               # `tab=$(printf '\t')` in POSIX
id='[[:digit:]]\+'
name='[[:alpha:]_][[:alnum:]_-]*'
grep "$name$tab$id"     # matches eg. `bob2<tab>323`