2011-04-22 71 views
0

如果一个div的孩子匹配某个字符串,我想删除整个div。例如:删除HTML标记,如果它包含一些文字

<div> 
some text here 
if this text is matched, remove whole div 
some other text 
</div> 

我必须在许多文件上这样做,所以我正在寻找一些像sed这样的Linux命令。

谢谢你关注此事。

+0

Yeah不使用正则表达式超文本标记语言,它会搞砸:http://stackoverflow.com/a/1732454/928098 – 2012-04-30 01:21:40

回答

0

有可能是一个更好的方式来做到这一点,但我已经在过去做的是:

1)剔除换行符(因为跨行匹配很难在最好的和倒退甚至更糟)

2)解析

3)把新行回

cat /tmp/data | tr "\n" "@" | sed -e 's/<div>[^<]*some text here[^<]*<\/div>//g' | tr "@" "\n"

这是假设 “@” 可以不会出现在文件中。

+0

呀,不使用正则表达式对HTML时,系统会去坏了:http://stackoverflow.com/a/1732454/928098 – 2012-04-30 01:21:04

1

如果我明白你的问题正确的话,就可以在一个单一的sed命令来实现:

sed '/<div>/I{:A;N;h;/<\/div>/I!{H;bA};/<\/div>/I{g;/\bsome text here\b/Id}}' file.txt 

测试

比方说,这是你的file.txt的:

a. no-div text 

<DIV> 

some text here 
1. if this text is matched, remove whole DIV 
some other text -- WILL MATCH 
</div> 

<div> 
awesome text here 
2. if this text is matched, remove whole DIV 
this will NOT be matched 
</div> 

b. no-div text 

<Div> 
another text here 
3. if this text is matched, remove whole DIV 
and this too will NOT be matched 
</Div> 

<div> 
Some TEXT Here 
4. if this text is matched, remove whole DIV 
foo bar foo bar - WILL MATCH 
</DIV> 

c. no-div text 

现在当我运行sed命令时,它给出了这个输出:

a. no-div text 


<div> 
awesome text here 
2. if this text is matched, remove whole DIV 
this will NOT be matched 
</div> 

b. no-div text 

<Div> 
another text here 
3. if this text is matched, remove whole DIV 
and this too will NOT be matched 
</Div> 


c. no-div text 

正如你可以从上面的输出验证模式some text here匹配div标签之间的那些div块已被完全删除。

PS:我在这里做大小写不敏感的搜索,如果你不需要这种行为请让我知道。我只需要从上面的sed命令中删除I开关。

+0

嗨@anubhava,你的代码看起来很棒,你能解释一下吗?例如:A命令 – 2013-03-12 07:39:36

0

您可以使用ed代替sed。 ed命令将整个文件读入内存并执行就地文件编辑(即不存在安全备份)。

htmlstr=' 
<see file.txt in answer by anubhava> 
' 
matchstr='[sS][oO][mM][eE]\ [tT][eE][xX][tT]\ [hH][eE][rR][eE]' 
divstr='[dD][iI][vV]' 
# for in-place file editing use "ed -s file" and replace ",p" with "w" 
# cf. http://wiki.bash-hackers.org/howto/edit-ed 
cat <<-EOF | sed -e 's/^ *//' -e 's/ *$//' -e '/^ *#/d' | ed -s <(echo "$htmlstr") 
    H 
    # ?re? The previous line containing the regular expression re. (see man ed) 
    # '[[:<:]]' and '[[:>:]]' match the null string at the beginning and end of a word respectively. (see man re_format) 
    #,g/[[:<:]]${matchstr}[[:>:]]/?<${divstr}>?,/<\/${divstr}>/d 
    ,g/[[:<:]]${matchstr}[[:>:]]/?<${divstr}>?+0,/<\/${divstr}>/+0d 
    ,p 
    q 
EOF 
相关问题