创建一个换行符的 Bash 脚本?

huangapple go评论53阅读模式
英文:

bash script creating a newline character?

问题

Hi I have a script to read 4.29.0 and convert to 4-29-0

The raw file I am reading is this:

$ cat package.xml | grep version
<?xml version="1.0"?>
<version>4.29.0</version>

The command I have to read is this:

VERSION=$(grep "version" package.xml | awk -F '>|<' '{print $3}' | sed 's/./-/g')

If I print it

echo "testing.. $VERSION"

This will print as follows

testing..
4-29-0

Why is there a new line character and how do I remove this? I want to see the string as

testing.. 4-29-0

英文:

Hi I have a script to read 4.29.0 and convert to 4-29-0

The raw file I am reading is this:

$ cat package.xml  | grep version
&lt;?xml version=&quot;1.0&quot;?&gt;
  &lt;version&gt;4.29.0&lt;/version&gt;

The command I have to read is this:

VERSION=$(grep &quot;version&quot; package.xml | awk -F &#39;&gt;|&lt;&#39; &#39;{print $3}&#39; | sed &#39;s/\./-/g&#39;)

If I print it

echo &quot;testing.. $VERSION&quot;

This will print as follows

testing.. 
4-29-0

Why is there a new line character and how do I remoev this ? I want to see the string as

testing.. 4-29-0

答案1

得分: 2

使用xmlstarlet

xmlstarlet edit --update '//version' -x 'translate(text(),".","-")' package.xml |
  xmlstarlet select --template --value-of '//version' -n

输出:

<pre>
4-29-0
</pre>

参见:xmlstarlet editxmlstarlet select

英文:

With xmlstarlet:

xmlstarlet edit --update &#39;//version&#39; -x &#39;translate(text(),&quot;.&quot;,&quot;-&quot;)&#39; package.xml |
  xmlstarlet select --template --value-of &#39;//version&#39; -n

Output:
<pre>
4-29-0
</pre>

See: xmlstarlet edit and xmlstarlet select

答案2

得分: 1

你的初始 [tag:grep] 不够集中。 你需要将

VERSION=$(grep "version" package.xml

更改为

VERSION=$(grep "<version>" package.xml

以确保只有包含相关内容的行将由awk命令处理。

英文:

Your initial [tag:grep] is not sufficiently focused. You need to change

VERSION=$(grep &quot;version&quot; package.xml

to

VERSION=$(grep &quot;&lt;version&gt;&quot; package.xml

to ensure only the line that has the relevant content will be processed by the awk command.

huangapple
  • 本文由 发表于 2023年3月7日 06:05:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定