Shell脚本根据参数将单个行转换为多行

时间:2013-07-23 07:19:39

标签: linux bash shell

我尝试为以下数据编写shell脚本

输入文件 page.txt ,内容为:

enter a first page title<br><div style="margin-left: 40px;">enter a first point <br></div><div style="margin-left: 80px;">enter a second point<br></div><div style="margin-left: 120px;">enter a third point<br></div><div style="margin-left: 80px;"><br></div><div style="margin-left: 40px;"><br></div><div style="margin-left: 40px;"><br></div>

算法:

Read the pages file
Replace <br> with newline
Replace <div style="margin-left: 40px;"> with 1 tab 
Replace <div style="margin-left: 80px;"> with 2 tab
Replace <div style="margin-left: 120px;"> with 3 tab
Replace <div style="margin-left: 160px;"> with 4 tab

我正在尝试使用此

tr '<br>' '\n' < page.txt

预期的输出文件

enter a first page title
    enter a first point 
        enter a second point
            enter a third point

请告诉我们如何编写上述脚本..

2 个答案:

答案 0 :(得分:1)

我不喜欢在没有解析器的情况下处理XML标记,但在这种特定情况下,您的数据看起来很奇怪(形成不良)所以以及在替换命令中评估替换字符串的选项是解决方案的好工具。

我使用三个替换命令,第一个使用换行符替换所有<br>,第二个用于删除所有关闭的div标记,第三个用于查找打开的div }标签,提取属性的数量,并使用它来计算要插入的标签数量:

perl -pe '
    s/<br>/\n/g; 
    s{</div>}{}g; 
    s{\Q<div style="margin-left: \E(\d+)\s*\Qpx;">}{"\t" x ($1/40)}ge
' infile

它产生:

enter a first page title
    enter a first point 
        enter a second point
            enter a third point

答案 1 :(得分:0)

最简单的方法是用\n替换行尾(不是<br>,而),如下所示:

(echo line one; echo line two) | sed -e 's/$/<br>/'

或在你的情况下:

sed -e 's/$/<br>/' < inputfile

使用插入符作为行首标记,类似地替换行开头的制表符。作为一个完整的脚本:

TAB="$(echo -e "\t")"
sed -e "s/^$TAB$TAB$TAB$TAB\(.*\)/<div style=\"margin-left: 160px;\">\1<\/div>/ \
    -e "s/^$TAB$TAB$TAB\(.*\)/<div style=\"margin-left: 120px;\">\1<\/div>/ \
    -e "s/^$TAB$TAB\(.*\)/<div style=\"margin-left: 80px;\">\1<\/div>/ \
    -e "s/^$TAB\(.*\)/<div style=\"margin-left: 40px;\">\1<\/div>/ \
    -e 's/$/<br>/' \
   < inputfile > outputfile

注1:末尾的\表示行继续,因此以上是2个陈述。

注意2:我假设你想在行尾添加</div>,只是为了显示/</div>的转义。

请注意,对于任何更复杂的内容,您应该考虑使用正确的提取和正则表达式语言,如Perl。您可能希望做一些事情,例如将多个行组合在一个<div>中以相同的方式缩进。