Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 保留具有特定关键字的行组(bash)_Linux_Search_Sed_Grep - Fatal编程技术网

Linux 保留具有特定关键字的行组(bash)

Linux 保留具有特定关键字的行组(bash),linux,search,sed,grep,Linux,Search,Sed,Grep,我有一个文本文件,其中有很多这样的行(每两行之间的行定义为一个组): 我应该从以#开头的行中搜索一些关键字(string,to),如果关键字在key.txt(一个包含两列的文件)中不存在,那么我应该删除该行和下面的(该组的)行。我编写的代码没有结果!(以输入文件中的关键字为例) cat input.txt |而IFS=$'#读取-r-a myarray 做 a=${myarray[1]} b=${myarray[0]} 取消设置IFS read-r a x y z$$&&mv$$input.tx

我有一个文本文件,其中有很多这样的行(每两行之间的行定义为一个组):

我应该从以#开头的行中搜索一些关键字(string,to),如果关键字在key.txt(一个包含两列的文件)中不存在,那么我应该删除该行和下面的(该组的)行。我编写的代码没有结果!(以输入文件中的关键字为例)

cat input.txt |而IFS=$'#读取-r-a myarray
做
a=${myarray[1]}
b=${myarray[0]}
取消设置IFS
read-r a x y z$$&&mv$$input.txt
fi
完成

有人能帮我吗?

获取正确数据块的简单方法是使用
awk
和正确的记录选择器:

awk 'FNR==NR {a[$0];next} { RS="#";for (i in a)  if ($0~i) print}' key.txt input.txt
 another string to examine
kinj 58 96 f
dfg 7 26 u
fds 9 76 j

这将重新插入所使用的
#
,并删除多余的空行。我可能有更简单的方法来做这件事,但这是可行的

awk 'FNR==NR {a[$0];next} { RS="#";for (i in a)  if ($0~i) {sub(/^ /,RS);sub(/\n$/,x);print}}' key.txt input.txt
#another string to examine
kinj 58 96 f
dfg 7 26 u
fds 9 76 j

向我们更新了
key.txt
中的数据,添加了第二个答案,以修复缺少的
#
并删除多余的空行。删除的空格在哪里?
awk 'FNR==NR {a[$0];next} { RS="#";for (i in a)  if ($0~i) print}' key.txt input.txt
 another string to examine
kinj 58 96 f
dfg 7 26 u
fds 9 76 j
awk 'FNR==NR {a[$0];next} { RS="#";for (i in a)  if ($0~i) {sub(/^ /,RS);sub(/\n$/,x);print}}' key.txt input.txt
#another string to examine
kinj 58 96 f
dfg 7 26 u
fds 9 76 j