如果在块中找到字符串,Shell脚本将删除整个块本身

问题描述 投票:-2回答:1

我有一个文本文件,其中包含如下数据。

server {
  listen 50;
  proxy_pass xyz:50;
  hivinu

所以我想通过将字符串作为xyz传递来删除上下行:有人可以给我解决方案吗?我尝试使用sed,但是我只能删除一个(循环)以下的行。但是我不确定如何使用sed或awk删除上面的行。

我通过传递xyz字符串来删除文件中的以下行,从而尝试了sed -ie'/ xyz:/,+ 1d命令。 –

一旦将字符串xyz传递给文件,我就需要输出,它应该删除完整的代码行并在文件中保留空白。

awk sed
1个回答
0
投票

您能不能尝试以下操作,在这里读取Input_file 2次。

awk '
FNR==NR{
  if($0~/xyz/){
    line_number=FNR
    nextfile
  }
  next
}
FNR<(line_number-2) || FNR>(line_number+1)
'  Input_file  Input_file

说明:添加以上代码的说明。

awk '                                          ##Starting awk code from here.
FNR==NR{                                       ##Checking condition FNR==NR which will be TRUE for first time Input_file is being read.
  if($0~/xyz/){                                ##Checking condition if a line contains string xyz then do following.
    line_number=FNR                            ##Assigning current line number to variable line_number here.
    nextfile                                   ##nextfile will STOP reading Input_file first time(GNU awk special).
  }
  next                                         ##next will skip all further statements from here.
}                                              ##Closing BLOCK for first time Input_file.
FNR<(line_number-1) || FNR>(line_number+1)     ##Cheking condition if current line number is lesser than line_number-1 AND greater than line_number+1 then print current line.
'  Input_file  Input_file                      ##Mentioning Input_file name here.
© www.soinside.com 2019 - 2024. All rights reserved.