0

我想在 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" />
4

3 回答 3

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))
于 2012-09-07T18:11:48.873 回答
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()) ;
于 2012-09-07T14:18:32.653 回答
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
于 2012-09-07T14:32:30.140 回答