在 unix 文件中查找以“#”开头的所有单词
Find all the words in a unix file which begin with '#'
输入文件看起来像这样:-
mary #had a little #lamb its #fleece #was white as snow
输出应该类似于
#had #lamb #fleece #was
使用sed
sed -r 's/(^| )[^#][^ ]+//g'
测试
echo "mary #had a little #lamb its #fleece #was white as snow" | sed -r 's/(^| )[^#][^ ]+//g'
#有一只#lamb #fleece #was
使用grep
grep -o "#[^ ]*"
测试
$ echo "mary #had a little #lamb its #fleece #was white as snow" | grep -o "#[^ ]*"
#had
#lamb
#fleece
#was
如果您不介意前导 space 并且不想匹配中间可能包含 #
的单词,例如 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
输入文件看起来像这样:-
mary #had a little #lamb its #fleece #was white as snow
输出应该类似于
#had #lamb #fleece #was
使用sed
sed -r 's/(^| )[^#][^ ]+//g'
测试
echo "mary #had a little #lamb its #fleece #was white as snow" | sed -r 's/(^| )[^#][^ ]+//g'
#有一只#lamb #fleece #was
使用grep
grep -o "#[^ ]*"
测试
$ echo "mary #had a little #lamb its #fleece #was white as snow" | grep -o "#[^ ]*"
#had
#lamb
#fleece
#was
如果您不介意前导 space 并且不想匹配中间可能包含 #
的单词,例如 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