如何使用grep来匹配空格或换行符 [英] how to use grep to match with either whitespace or newline

查看:1086
本文介绍了如何使用grep来匹配空格或换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用单词grep一个文件,说AAA,并以空白或换行符结尾。我知道如何单独编写它,如下所示,但在组合它们时存在问题(从输出 VVV AAA AAA VVV )。

I want to grep a file with a word, say "AAA", and it ends with whitespace or newlines. I know how to write this seperately, as follows, but having problems in combining them (in the sense that it outputs both VVV AAA and AAA VVV).

$echo -e "AAA VVV \nVVV AAA\nBBB" | grep "AAA$" 
>VVV AAA
$echo -e "AAA VVV \nVVV AAA\nBBB" | grep "AAA[[:space:]]" 
>AAA VVV 

我有尝试使用 [] ,但没有成功..

I have tried using [], but without success..

推荐答案

正在查找单词 AAA ,然后在字符串中的任意位置或行尾查找空格,然后使用

If you are looking for word AAA followed by space anywhere in the string, or at the end of line, then use

grep -P "AAA( |$)"

这篇关于如何使用grep来匹配空格或换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆