2013-11-21 45 views
1

我需要搜索文件中的特定字符串,並刪除文件中的所有行,直到我再次到達特定字符串。基本上我需要刪除兩個特定字符串之間的所有行。

需要使用shell腳本刪除txt文件中的特定行

<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> 
+2

你有什麼企圖? – jmstoker

+0

您有問題嗎? – Kenosis

回答

3
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 
+0

謝謝@Amadan。如何使用shell腳本執行相同的操作? – user2589079

+1

*是* shell腳本。所有的shell腳本都在調用各種可執行文件來執行各種相互結合的小任務。 '/ bin/cat'和'/ usr/bin/perl'之間沒有區別,只是後者更加靈活。 – Amadan

+0

但是這需要在盒子上安裝perl。糾正我,如果我錯了。我相信大部分unix盒都安裝了perl,但我不想在特殊情況下。謝謝回覆。 – user2589079

相關問題