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))