使用sed剪切文件的一部分

时间:2015-05-31 17:36:57

标签: bash sed

cat /opt/inventory.txt

###################################################################################
Begin_detail_of 5678
Request_No of the activity is 5678
testProject
Requester of the project is xyz
xyz@test.com
End_of 5678
####################################################################################
###################################################################################
Begin_detail_of 1234
Request_No of the activity is 1234
testProject
Requester of the project is xyz
xyz@test.com
End_of 1234
####################################################################################

当我使用下面的数字1234时,我得到预期输出

cat /opt/inventory.txt | sed -n -e '/Begin_detail_of\ 5678/,$p' | sed -e '/End_of\ 5678/,$d'
Begin_detail_of 5678
Request_No of the activity is 5678
testProject
Requester of the project is xyz
xyz@test.com
You have new mail in /var/spool/mail/root

但是当我用变量输出替换数字时不如下所示

[root@centoo script]# export num=5678
[root@centoo script]# echo $num
5678
[root@centoo script]# cat /opt/inventory.txt | sed -n -e '/Begin_detail_of\ $num/,$p' | sed -e '/End_of\ $num/,$d'
[root@centoo script]#

请帮助解决问题。

4 个答案:

答案 0 :(得分:3)

您不需要2个sed命令,并确保在表达式中使用shell变量时使用双引号。你可以在同一个sed中执行此操作:

num=5678
sed -n "/Begin_detail_of $num/,/End_of $num/{/End_of $num/d;p;}" file
Begin_detail_of 5678
Request_No of the activity is 5678
testProject
Requester of the project is xyz
xyz@test.com

答案 1 :(得分:1)

你使用了错误的工具,sed不适用于跨越多行的任何东西。只需使用标准的UNIX文本处理工具awk。这是多字符RS的GNU awk:

$ gawk -v tgt='5678' -v RS='#+\n' -v ORS= '$0~"Begin_detail_of "tgt"\n"' file
Begin_detail_of 5678
Request_No of the activity is 5678
testProject
Requester of the project is xyz
xyz@test.com
End_of 5678

$ gawk -v tgt='1234' -v RS='#+\n' -v ORS= '$0~"Begin_detail_of "tgt"\n"' file
Begin_detail_of 1234
Request_No of the activity is 1234
testProject
Requester of the project is xyz
xyz@test.com
End_of 1234

如果你想删除第一行和最后一行:

$ gawk -v tgt='5678' -v RS='End_of[^\n]+\n#+\n' -v ORS= 'sub("#+\nBegin_detail_of "tgt"\n","")' file
Request_No of the activity is 5678
testProject
Requester of the project is xyz
xyz@test.com

$ gawk -v tgt='1234' -v RS='End_of[^\n]+\n#+\n' -v ORS= 'sub("#+\nBegin_detail_of "tgt"\n","")' file
Request_No of the activity is 1234
testProject
Requester of the project is xyz
xyz@test.com

无论你想做什么都是简短而微不足道的,因为这就是awk的目的。

答案 2 :(得分:0)

使用awk

awk -v RS="###################################################################################" /"End_of $num"/ file

答案 3 :(得分:0)

双引号中的变量(某些单词以$开头)将被添加到其内容中,而单引号中的变量则不会。这是shell的特色。因此,如果要动态生成sed命令,只需使用单引号。