2012-12-28 46 views
2

在两行文本之间搜索和删除数据的最佳方式是什么?包括第一行而不是第二行。在两行之间删除数据

串1:SECTION - PAY 500 - 要删除

数据被删除,文字的随机线

字符串2:SECTION - Pay 400 - 保持

这是Word文档是围绕3000页,但我也有一个文本版本可以使用。我会在哪里开始为这样的任务编写一个bash脚本?文件内容的

例如:

text 
SECTION - PAY 500 (to be deleted) 
text     (to be deleted) 
SECTION - Pay 400 
text 
SECTION - PAY 500 (to be deleted) 
text     (to be deleted) 
SECTION - Pay 400 
text 

删除后,这应该是结果

text 
SECTION - Pay 400 
text 
SECTION - Pay 400 
text 
+1

假设你正在寻找从3000页的文档删除了许多块,你可以给我们更多的例子。您希望删除多少个块?各节标记中的文本之间是否有不明确之处,即“SECTION - PAY 5000”?祝你好运。 – shellter

+2

'sed'会是我去这里。兄弟',非常好的一个, – squiguy

回答

3

解决方案与标准sed

sed "/$START/,/$END/ { /$END/"'!'" d; }" 

这意味着,对于范围从/$START/开始,结束于/$END/将执行{ /$END/! d; }操作,对于并非/$END/的所有行,该操作不会执行d(删除)。

"'!'"只是很奇怪,但从bash扩展中逃脱!符号的唯一方法。

+0

! – Rubens

0

我认为你可以很快地逐行解析文件。你正在做什么似乎没有太复杂的实现。

copy=true 
while read line; do 
    if [ $copy ]; then 
     if [[ "$line" == "SECTION - PAY 500"* ]]; then copy=; continue; fi 
     echo "$line" >> outputfile 
    else 
     if [[ "$line" == "SECTION - Pay 400"* ]]; then copy=true; fi 
    fi 
done < inputfile 

并通过这样做,我们甚至有一些像一个小图灵机吧!

0

另一个(少怪异;))标准SED解决方案: sed "/$END/ p; /$START/,/$END/ d;"

边注:某些sed版本还支持就地文件的编辑,如果需要的话。

而一个完全成熟的bash脚本:

#! /bin/bash 

if [ "x$1" = "x-r" ] 
then 
    regex=1 
    shift 
else 
    regex=0 
fi 

if [ $# -lt 2 ] 
then 
    echo "Usage: del.sh [-r] start end" 
    exit 1 
fi 

start="$1" 
end="$2" 

function matches 
{ 
    [[ (regex -eq 1 && "$1" =~ $2) || (regex -eq 0 && "$1" == "$2") ]] 
} 

del=0 
while read line 
do 
    # end marker, must be printed 
    if matches "$line" "$end" 
    then 
     del=0 
    fi 
    # start marker, must be deleted 
    if matches "$line" "$start" 
    then 
     del=1 
    fi 
    if [ $del -eq 0 ] 
    then 
     echo "$line" 
    fi 
done 
0

简单的解决方案:尝试这种方式

Inputfile.txt

text 
SECTION - PAY 500  
text     
SECTION - Pay 400 
text 
SECTION - PAY 500 
text     
SECTION - Pay 400 
text 

代码

awk '/500/{print;getline;next}1' Inputfile.txt | sed '/500/d' 

输出

text 
SECTION - Pay 400 
text 
SECTION - Pay 400 
text 
相关问题