【发布时间】:2018-11-22 08:51:20
【问题描述】:
我是个 awk 新手。我有一个看起来像这样的文件:
beans and celery
beans and oatmeal
beans and beans
quinoa
<fo:external-graphic width="auto" height="auto" content-width="36pt" src="url(file:/C:/Users/xxx/images/tip.svg)"/>
<fo:external-graphic src="url(images/image1.png)" width="6.3in" height="auto" content-width="246px" content-height="322px"/>
我正在尝试执行搜索并就地替换“fo”标签。我想捕获标签的开头,以及“src”参数。请注意,src 标签的位置因行而异!
我已经能够使用以下方法获得我想要的字段:
awk '/<fo:external-graphic.*/ {for (i=1; i<=NF; ++i) {if ($i ~ "src") print $1 " " $i}}' inventory.txt
如何进行就地替换? 我还想将一个字符串附加到该行的新内容。我试过了:
awk '/<fo:external-graphic.*/ {for (i=1; i<=NF; ++i) {if ($i ~ "src") print $1 " " $i "misc stuff here"}}' inventory.txt
但它完全打乱了结果字符串的顺序,我希望它的形式是:
<fo:external-graphic src="url(images/image1.png)" misc stuff here
PS1: 进一步澄清我想要什么结果: 该文件包含如下字符串:
<fo:external-graphic width="auto" height="auto" content-width="36pt" src="url(file:/C:/Users/xxx/images/tip.svg)"/>
<fo:external-graphic src="url(images/image1.png)" width="6.3in" height="auto" content-width="246px" content-height="322px"/>
我想处理这些并获得如下输出:
<fo:external-graphic src="url(images/image1.png)" _completely new stuff here, till end of string_ />
例如:
<fo:external-graphic src="url(images/image1.png)" age="25" sex="M" />
我希望结果始终以:
<fo:external-graphic src="url(images/image1.png)"
然后是额外的东西,例如:
age="25" sex="M" />
在最终输出中不需要原始字符串的其他部分。
PS2:我可以将所有这些打包到 gsub 中吗?据我所知,gsub 只接受两个参数。我试图为 replace 参数制作一个复杂的表达式,但它一直失败,例如:
gawk '/<fo:external-graphic.*/ {for (i=1; i<=NF; ++i) {if ($i ~ "src") gsub($0, "boy band"); {print}}}' inventory.txt > testres
PS3:这只是一个新手观察,也许我错了。考虑一个包含以下内容的文件:
Donald Trump
Donald Duck
George Bush
Steve Austin
搜索所有以 Donald 开头的行的正则表达式是:
/^Donald/
如果我想用“Barrack”替换所有出现的“Donald”,我可以执行以下操作:
gawk -i inplace '{ gsub(/^Donald/, "Barrack"); { print } }' FILENAME
如果我想完全更改所有包含“Donald”的行,我会这样做:
gawk -i inplace '{ gsub(/^Donald.*/, "Barrack"); { print } }' FILENAME
gawk 和 gsub 似乎只替换 span 或字符串的任何部分与给定的正则表达式匹配。因此,如果我想完全改变一整行,我的正则表达式应该跨越整行。
PS4:只是为了澄清我所期望的解决方案的任何歧义。给定以下文件:
<fo:external-graphic width="auto" height="auto" content-width="36pt" src="url(file:/C:/Users/xxx/images/tip.svg)"/>
<fo:external-graphic width="6.3in" height="auto" src="url(images/image1.png)" content-width="246px" content-height="322px"/>
<fo:external-graphic src="url(images/image1.png)" width="6.3in" content-width="246px" content-height="322px"/>
我正在寻找一种 awk/gawk 解决方案,该解决方案将把这个文件替换为:
<fo:external-graphic src="url(file:/C:/Users/xxx/images/tip.svg)" age="25" sex="M" />
<fo:external-graphic src="url(images/image1.png)" age="25" sex="M"/>
<fo:external-graphic src="url(images/image1.png)" age="25" sex="M"/>
目标文件必须更改。
【问题讨论】:
-
@Inian 似乎没有更新文件。请查看我更新的问题以查看我期望的最终答案的形式!
-
@RavinderSingh13 请查看我的问题的最新更新!如果您有任何疑问,请告诉我。谢谢
-
@Inian 请查看我的问题的最新更新!如果您有任何疑问,请告诉我。谢谢
-
我的最后一次更新应该可以解决您的问题
标签: awk