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


当前回答

+1方式,工作在ksh,破折号等:使用printf插入制表符:

grep "$(printf 'BEGIN\tEND')" testfile.txt

其他回答

基本上有两种解决方法:

(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 ...

我从来没有设法使“\t”元字符与grep一起工作。 然而,我发现了两个替代方案:

使用<Ctrl-V> <TAB>(按Ctrl-V然后输入TAB) 使用awk: foo | awk '/\t/'

使用gawk,将字段分隔符设置为TAB (\t)并检查字段的数量。如果多于1,则有/有制表符

awk -F"\t" 'NF>1' file

一种方法是(这是Bash)

grep -P '\t'

-P将打开Perl正则表达式,因此\t将工作。

正如用户unwind所说,它可能是特定于GNU grep的。另一种方法是在shell、编辑器或终端允许的情况下插入一个制表符。

你可以打字 Grep \t foo 或

grep '\t' foo

在文件foo中搜索制表符。您可能还可以使用其他转义代码,尽管我只测试了\n。虽然这相当耗时,而且不清楚为什么要这样做,但在zsh中,您还可以键入制表符,回到开头,grep并将制表符用引号括起来。