查找以'#'开头的unix文件中的所有单词

时间:2015-01-23 17:33:55

标签: unix awk sed

输入文件看起来像这样: -

mary #had a little #lamb its #fleece #was white as snow

输出应该看起来像

#had #lamb #fleece #was

2 个答案:

答案 0 :(得分:1)

使用sed

sed -r 's/(^| )[^#][^ ]+//g'

<强>测试

echo "mary #had a little #lamb its #fleece #was white as snow" | sed -r 's/(^| )[^#][^ ]+//g'

#had #lamb #fleece #was

使用grep

grep -o "#[^ ]*"

<强>测试

$ echo "mary #had a little #lamb its #fleece #was white as snow" | grep -o "#[^ ]*"
#had
#lamb
#fleece
#was

答案 1 :(得分:0)

如果你不介意一个领先的空间,并且不想匹配中间可能包含#的单词,例如lit#tle,你也可以试试这个:

grep -o -P "(\s|^)#\w+"

示例:

echo "#mary #had a lit#tle #lamb its #fleece #was white as snow" | grep -o -P "(\s|^)#\w+"
#mary
 #had
 #lamb
 #fleece
 #was