我有一个包含以下内容的大文本文件:
Register foo1 ... Register foo2 ... Register foo10...
Register foo20 ...
Un-Register bar1 ... Register foo21 ...
我在下面写了一个bash脚本,只有当有一个" Register"每行,但如何让所有foo在同一行?
#!/bin/bash
file=/tmp/log
grep -e 'Register\s' $file | awk '{print $2}' | grep -v Un-Register | while read -r line; do
#do something with $line
done
答案 0 :(得分:0)
试试这个:
perl -pe 's/\s+Register/\nRegister/g' file |
grep -oP '^Register\s+\Kfoo\S*'
foo1
foo2
foo10...
foo20
foo21
答案 1 :(得分:0)
这是一个perl单行程序,用于在“注册”之后找到该单词而不是“取消注册”,并且一行中的所有单词将保留在一行
$ perl -nE 'say "@{[/(?<!Un-)Register\s+\K\S+/g]}"' file
foo1 foo2 foo10...
foo20
foo21
密度较低的版本:
$ perl -nE '
@words = / (?<!Un-) # preceding characters are not "Un-"
Register \s+ # must have "Register" followed by whitespace
\K # disregard the previous from matching
\S+ # capture the next non-whitespace characters
/gx; # "g"lobally on this line
say "@words";
' file
答案 2 :(得分:0)
以下是完成工作的非正则表达式awk
解决方案:
awk '{
s=""
for (i=2; i<=NF; i++)
if ($(i-1) == "Register")
s = sprintf("%s%s", (s==""?"":s OFS), $i)
print s
}' file
foo1 foo2 foo10...
foo20
foo21
答案 3 :(得分:0)
egrep -o '(^|[^-])Register \w*' file | awk '{print $2 }'
Register word
(而不是Un-Register
)并在新行中打印匹配项(-o
选项)awk
仅打印