【问题标题】:Need to remove a specific lines in txt file using shell script [closed]需要使用 shell 脚本删除 txt 文件中的特定行 [关闭]
【发布时间】:2013-11-21 00:36:58
【问题描述】:

我需要在文件中搜索特定字符串并删除文件中的所有行,直到我再次找到特定字符串。基本上我需要删除两个特定字符串之间的所有行。
例如

 <start /myhome >
 some entries
 some entries
 <end>
 <start ~ "/myhome[^/]+" >
 some entries
 some entries
 <end>
 <start /newhome >
 some entries
 some entries
 another entry
 different string
 <end>
 <start ~ "/myhome[^/]+" >
 some entries
 some entries
 <end>

预期的输出应该是:

<start /myhome >
 some entries
 some entries
 <end>
 <start /newhome >
 some entries
 some entries
 another entry
 different string
 <end> 

【问题讨论】:

  • 你尝试了什么?
  • 您有问题吗?

标签: regex perl bash shell perlscript


【解决方案1】:
perl -ne 'print if !(/<start.*?myhome\[.*?>/ .. /<end>/);' < file.txt

编辑:好吧,如果您只想使用内置函数...

#!/bin/sh                                                                       

hide_from_to() {
  start=$1
  end=$2
  unset hide

  while read line
  do
    if test "$line" = "$start"
    then
      hide=1
    fi
    if test -z "$hide"
    then
      echo $line
    fi
    if test "$line" = "$end"
    then
      unset hide
    fi
  done
}

hide_from_to '<start ~ "/myhome[^/]+" >' '<end>' < a.txt

【讨论】:

  • 谢谢@Amadan。如何对 shell 脚本做同样的事情?
  • shell脚本。所有的 shell 脚本都在调用各种可执行文件来执行各种相互结合的小任务。 /bin/cat/usr/bin/perl没有区别,只是后者更灵活一点。
  • 但这需要在盒子上安装perl。如果我错了,请纠正我。我确信大多数 unix 机器都安装了 perl,但我不想在特殊情况下。感谢您的回复。
  • @user2589079 几乎所有个UNIXY盒子都有Perl。
  • @Amdan 我已经测试了一个班轮,非常感谢。我有一个问题,上述两种解决方案都将输出在其中。有没有办法只更新现有文件或重定向到新文件。然后我可以用原来的重命名它。让我知道你的建议。
猜你喜欢
  • 2018-12-22
  • 2022-07-11
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
  • 2022-10-23
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
相关资源
最近更新 更多