sed在文件上等于变量

时间:2017-06-27 17:34:50

标签: linux bash macos shell sed

这是我的shell命令:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="foo" xmlns:xsi="bar"
         xsi:schemaLocation="foo">
  <myTag>
   .... several tags inside...
  </myTag>
</project>
不幸的是,&#39;佩里&#39;变量从不打印,它只是打印一个空白行,这里发生了什么?

示例xml:

install.packages("partykit")
Installing package into ‘C:/Users/ckingshuk/Documents/R/win-library/3.3’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.3/partykit_1.1-1.zip'
Content type 'application/zip' length 1231797 bytes (1.2 MB)
downloaded 1.2 MB

Error in install.packages : cannot open file 'C:/Users/ckingshuk/Documents/R/win-library/3.3/file1f88479a12e2/partykit/doc/constparty.pdf': Permission denied

我的最终目标是捕获标准xml文件之间的所有内容,然后运行一个“awk”&#39;命令它来替换某些部分(在递增版本号之后),只是fyi。

谢谢!

2 个答案:

答案 0 :(得分:1)

您正在使用反引号和$()来执行第二个分配中的命令。它们都执行包含的命令并将其替换回命令行。因此sed的结果被视为执行命令,其输出被放入perry。由于标记的内容可能不是有效命令,因此第二次执行会出错。

不要在shell中使用反引号,只需使用$()

temp=$(cat ./myFile.xml)
perry=$(echo "$temp"| sed -n 's:.*<myTag>\(.*\)</myTag>.*:\1:p')
echo "$perry"

但是,只有当<myTag></myTag>位于同一行时才会有效,因为sed一次只能操作一行。所以它不适用于您在问题中发布的示例文件(我在添加之前写了上面的答案)。 用于从XML文件中提取数据的更好工具是xmlstarlet

答案 1 :(得分:0)

如果您稍后要使用awk,请从头开始使用它:

awk '{ if ($0 ~ /<myTag>/) {strt=1} if (strt==1) {print $0} if ($0 ~ /<\/myTag>/) {strt=0} }' myfile.xml

如果匹配,每行与“”匹配模式,我们开始设置strt = 1并开始打印文本。如果模式匹配“”,我们设置strt = 0并停止打印。

您可以添加到脚本中以更改标记。