我有一个文件Query.txt,其数据如下:
# Query: Name_ID
# 2 hits found****
# Query: Name_ID
# 20 hits found
# Query: Name_ID
# 0 hits found
当我使用它或grep它获取模式时,我得到如下输出:
grep "0 hits found" Query.txt | head
# 20 hits found
# 0 hits found
# 140 hits found
# 70 hits found
两个问题: 我如何专门得到“0次点击”而不是20或140或70? 第二,如何使用AWK创建另一个文件Query2.txt,格式如下?
# Query: Name_ID # 2 hits found
# Query: Name_ID # 20 hits found
# Query: Name_ID # 0 hits found
答案 0 :(得分:5)
要仅获取0 hits found
行,请尝试匹配该字符串,但在零之前没有数字:
awk '$0 ~ /[^[:digit:]]0 hits found/' infile
假设测试输入文件(infile
)如:
# Query: Name_ID1
# 2 hits found
# Query: Name_ID2
# 20 hits found
# Query: Name_ID3
# 0 hits found
# Query: Name_ID4
# 140 hits found
# Query: Name_ID5
# 0 hits found
# Query: Name_ID6
# 60 hits found
它产生:
# 0 hits found
# 0 hits found
对于第二个问题,请使用getline
读取奇数行并同时打印,例如:
awk '{ getline hits_line; printf "%s %s\n", $0, hits_line }' infile
使用与以前相同的测试文件,它产生:
# Query: Name_ID1 # 2 hits found
# Query: Name_ID2 # 20 hits found
# Query: Name_ID3 # 0 hits found
# Query: Name_ID4 # 140 hits found
# Query: Name_ID5 # 0 hits found
# Query: Name_ID6 # 60 hits found
另外,我也喜欢使用vim尝试这种任务,所以这里有一个解决方案:
script.vim
的内容:
set backup
for n in range( 1, line('$') / 2 )
execute "normal Jj"
endfor
saveas! Query2.txt
q!
像以下一样运行:
vim -S script.vim infile
这将生成包含内容的Query2.txt
文件:
# Query: Name_ID1 # 2 hits found
# Query: Name_ID2 # 20 hits found
# Query: Name_ID3 # 0 hits found
# Query: Name_ID4 # 140 hits found
# Query: Name_ID5 # 0 hits found
# Query: Name_ID6 # 60 hits found
答案 1 :(得分:1)
sed '/\s0/!d' file
(为什么“点击发现”?)
awk '/\y0/' file
答案 2 :(得分:0)
你只需要在0之前添加一个单词边界:
grep '\<0 hits found' Query.txt
你可以用
来实现第二部分paste - - < Query.txt
基本上,这会连接文件中的每两行。
答案 3 :(得分:0)
使用sed
sed -n 'N;/\<0 hits/{s/\n/ /;P}' Query.txt
[jaypal:~/Temp] cat Query.txt
# Query: Name_ID
# 2 hits found****
# Query: Name_ID
# 20 hits found
# Query: Name_ID
# 0 hits found
[jaypal:~/Temp] sed -n 'N;/\<0 hits/{s/\n/ /;P}' Query.txt
# Query: Name_ID # 0 hits found