2009-07-22 453 views
6

我有一个sed命令,我想在一个巨大的,可怕的,丑陋的HTML文件上创建一个Microsoft Word文档。所有应该做的是去除串在sed中匹配任何字符(包括换行符)

style='text-align:center; color:blue; 
exampleStyle:exampleValue' 

sed命令,我想修改的任何实例是

sed "s/ style='[^']*'//" fileA > fileB 

它的伟大工程,但每当有内部的新行匹配文本,它不匹配。有没有sed的修饰符,或者我可以做什么来强制匹配任何字符,包括换行符?

我明白在XML和HTML中,正则表达式很糟糕,但是在这种情况下,字符串模式是格式良好的,因为样式属性总是以单引号开头并以单引号结尾。所以,如果我能解决换行问题,那么只需一条命令即可将HTML大小缩减50%以上。


最后,事实证明,SinanÜnür的perl脚本效果最好。它几乎是瞬间的,它将文件大小从2.3 MB降低到了850k。好醇'Perl ...

+0

sed是基于行的。这是这里的主要停止点。如果你使用/ g正则表达式修饰符,可能会有一个命令行选项让它读取文件作为一个'行',但我怀疑它(内存问题等) – 2009-07-22 12:39:10

+0

没有选择(我知道)用于单个文件读取文件。我会为此使用Perl。 – Dana 2009-07-22 12:42:07

回答

2

sed越过输入文件行,这意味着,据我所知,你想要什么是不可能在sed

您可以使用下面的Perl脚本(未经测试),虽然:

#!/usr/bin/perl 

use strict; 
use warnings; 

{ 
    local $/; # slurp mode 
    my $html = <>; 
    $html =~ s/ style='[^']*'//g; 
    print $html; 
} 

__END__ 

一个一个班轮将是:

$ perl -e 'local $/; $_ = <>; s/ style=\047[^\047]*\047//g; print' fileA > fileB 
1

你可以删除使用tr所有CR/LF,运行sed,然后导入到自动格式化的编辑器中。

3

Sed一行一行地读取输入,所以在一行上处理并不简单......但也不是不可能的,你需要使用sed分支。下面的工作,我曾评论它来解释什么是要去(不是最易读的语法!):

sed "# if the line matches 'style='', then branch to label, 
    # otherwise process next line 
    /style='/b style 
    b 
    # the line contains 'style', try to do a replace 
    : style 
    s/ style='[^']*'// 
    # if the replace worked, then process next line 
    t 
    # otherwise append the next line to the pattern space and try again. 
    N 
    b style 
" fileA > fileB 
1

你可以试试这个:

awk '/style/&&/exampleValue/{ 
    gsub(/style.*exampleValue\047/,"") 
} 
/style/&&!/exampleValue/{  
    gsub(/style.* /,"") 
    f=1   
} 
f &&/exampleValue/{ 
    gsub(/.*exampleValue\047 /,"") 
    f=0 
} 
1 
' file 

输出:

# more file 
this is a line 
    style='text-align:center; color:blue; exampleStyle:exampleValue' 
this is a line 
blah 
blah 
style='text-align:center; color:blue; 
exampleStyle:exampleValue' blah blah.... 

# ./test.sh 
this is a line 

this is a line 
blah 
blah 
blah blah.... 
1

另一种方式是:

$ cat toreplace.txt 
I want to make \ 
this into one line 

I also want to \ 
merge this line 

$ sed -e 'N;N;s/\\\n//g;P;D;' toreplace.txt 

输出:

I want to make this into one line 

I also want to merge this line 

N负载另一条线,P打印模式空间到第一换行,并删除D模式空间直到第一换行符。

相关问题