如何在Unix平台上的文件中grep标签(\t) ?
当前回答
我从来没有设法使“\t”元字符与grep一起工作。 然而,我发现了两个替代方案:
使用<Ctrl-V> <TAB>(按Ctrl-V然后输入TAB) 使用awk: foo | awk '/\t/'
其他回答
在表达式中插入制表符的另一种方法是使用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`
下面是问Ubuntu的答案:
告诉grep使用由Perl定义的正则表达式(Perl拥有 \t as tab): grep -P "\t" <文件名称> . grep "\t" <文件名称> . grep "\t 使用文字制表符: grep "^V<tab>" <文件名> . grep "^V<tab> 使用printf打印制表符: Grep "$(printf '\t')"<文件名>
一种方法是(这是Bash)
grep -P '\t'
-P将打开Perl正则表达式,因此\t将工作。
正如用户unwind所说,它可能是特定于GNU grep的。另一种方法是在shell、编辑器或终端允许的情况下插入一个制表符。
+1方式,工作在ksh,破折号等:使用printf插入制表符:
grep "$(printf 'BEGIN\tEND')" testfile.txt
These alternative binary identification methods are totally functional. And, I really like the one's using awk, as I couldn't quite remember the syntaxic use with single binary chars. However, it should also be possible to assign a shell variable a value in a POSIX portable fashion (i.e. TAB=echo "@" | tr "\100" "\011"), and then employ it from there everywhere, in a POSIX portable fashion; as well (i.e grep "$TAB" filename). While this solution works well with TAB, it will also work well other binary chars, when another desired binary value is used in the assignment (instead of the value for the TAB character to 'tr').
推荐文章
- 匹配前后的Grep字符?
- (grep)正则表达式匹配非ascii字符?
- 如何从另一个文件A中删除文件B中出现的行?
- 对以制表符分隔的文件进行排序
- 如何使用查找命令从列表中查找所有具有扩展名的文件?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 在Bash中获取日期(比当前时间早一天)
- Linux: kill后台任务
- 在OSX中永久设置PATH环境变量
- PowerShell等价于grep -f
- 如何在C程序中获取当前目录?
- 如何在Bash中逐行合并两个文件
- 如何从远程SSH会话发送数据到本地剪贴板
- 我如何得到bash完成工作与别名?
- SSH端口转发~/。ssh /配置文件?