用不同的结构替换结构并保留一些值

时间:2012-09-07 14:07:41

标签: bash

我想在bash中将输入传输到输出。我尝试使用sed但它没有用 - 我可能有错。到目前为止,我有这个(只是尝试,如果我可以提取id)但它不起作用:

sed 's;id="([a-zA-Z:]+)";\\1;p' input

输入

<mediaobject>
    <imageobject id="fig:deployment">
        <caption>Application deployment</caption>
        <imagedata fileref="images/deployment.png" width="90%" />
    </imageobject>
</mediaobject>

输出

<img src="images/deployment.png" width="90%" id="fig:deployment" title="Application deployment" />

3 个答案:

答案 0 :(得分:3)

awk几乎可以在任何安装了bash的地方使用,并且可以避免使用sed时遇到的一些陷阱(例如,如果xml中的属性没有一致排序)。

awk '
    ## set a variable to mark that we are in a mediaobject block
    $1=="<mediaobject>" { object=1 }

    ## mark that we have exited the object block
    $1=="</mediaobject>" { object=0 }

    ## if we are in an mediaobject block and we find an imageblock
    $1=="<imageobject" && object==1 { 
        iobject=1                          ## record that we are in an imageblock
        id = substr($2, 5, length($2) - 6) ## this is unnecessary for output
    }

    ## if we have a line with image data
    $1~/<imagedata/ && iobject==1 {
        fileref=substr($2,9,length($2)-8)  ## the path, including the quotations
        width=$3                           ## the width
    }

    ## if we have a caption line
    $1~/<caption>/ && iobject==1 {
        gsub("(</?caption>|^ *| *$)", "")  ## remove xml and leading/trailing whitespace
        caption=$0                         ## record the modified line as the caption
    }

    ## when we arrive at the end of an imageblock
    $1=="</imageobject>" && object==1 {
        iobject=0                                                            ## record it
        printf("<img src=%s %s title=\"%s\" />\n", fileref, width, caption)  ## print record
    }

' input

虽然正如我所提到的,无论属性如何定型,此代码都应该同样有效,如果行上的属性改变顺序(不太可能),它将失败。如果遇到这个问题,可以执行以下操作:

## use match to find the beginning of the attribute
## use a nested substr() to pull only the value of fileref (with quotations)
fileref = substr(substr($0, match($0,/fileref=[a-z\/"]+/),RLENGTH),9))

答案 1 :(得分:0)

使用xsh

open 1.xml ;
rename img mediaobject ;
mv img/imageobject/@id into img ;
set img/@title img/imageobject/caption ;
set img/@src img/imageobject/imagedata/@fileref ;
mv img/imageobject/imagedata/@width into img ;
rm (img/* | img/text()) ;

答案 2 :(得分:0)

使用sed:

 sed -n '\!<mediaobject>!{
  n;
  s/ *[^ ]* \(id="[^"]*"\).*/\1/; 
  h; n;
  s/ *[^>]*>\([^<]*\).*/title="\1"/;
  H; n;
  s/ *<[^ ]* *fileref=\("[^"]*"\) *\(width="[^"]*"\).*/src=\1 \2/;
  H; n;
  x;
  s/\n/ /g;
  s/^/<img /;
  s/$/ \/>/;
  p
 }' input