使用bash更新属性文件中的版本号
我是bash脚本新手,需要awk方面的帮助。问题是我有一个属性文件,里面有版本,我想更新它使用bash更新属性文件中的版本号,bash,shell,Bash,Shell,我是bash脚本新手,需要awk方面的帮助。问题是我有一个属性文件,里面有版本,我想更新它 version=1.1.1.0 我用awk来做这件事 file="version.properties" awk -F'["]' -v OFS='"' '/version=/{ split($4,a,"."); $4=a[1]"."a[2]"."a[3]"."a[4]+1 } ;1' $file > newFile && mv newFile $file
version=1.1.1.0
我用awk来做这件事
file="version.properties"
awk -F'["]' -v OFS='"' '/version=/{
split($4,a,".");
$4=a[1]"."a[2]"."a[3]"."a[4]+1
}
;1' $file > newFile && mv newFile $file
但我得到了奇怪的结果version=“1.1.1.0”…1
有人能帮我一下吗。你可以用
=
作为分隔符,如下所示:
awk -F= -v v=1.0.1 '$1=="version"{printf "version=\"%s\"\n", v}' file.properties
这不是最好的方法,但有一个解决办法 测试用例 我假设输入文件至少有一行正好是
version=1.1.1.0
$ awk -F'["]' -v OFS='"' '/version=/{
> split($4,a,".");
> $4=a[1]"."a[2]"."a[3]"."a[4]+1
> }
> ;1' <<<'version=1.1.1.0'
“
是因为您正在分配给字段4($4
)。执行此操作时,awk会在字段1和2、2和3以及3和4之间添加字段分隔符(OFS
)。在您的示例中,有三个OF
=>“”
最小变化
$awk-F'[“]'-v OFS=''''''''/version=/{
拆分($1,a,“.”);
$1=a[1]。“a[2]。“a[3]。”a[4]+1;
打印
}
“您在评论中提到,您希望就地更新文件。您可以使用perl以一行程序的形式进行更新:
perl -pe '/^version=/ and s/(\d+\.\d+\.\d+\.)(\d+)/$1 . ($2+1)/e' -i version.properties
解释
-e
后面跟着一个要运行的脚本。使用-p
和-i
,效果是在每一行上运行该脚本,并在脚本发生任何更改时修改文件
为了便于解释,脚本本身是:
/^version=/ and # Do the following on lines starting with `version=`
s/ # Make a replacement on those lines
(\d+\.\d+\.\d+\.)(\d+)/ # Match x.y.z.w, and set $1 = `x.y.z.` and $2 = `w`
$1 . ($2+1)/ # Replace x.y.z.w with a copy of $1, followed by w+1
e # This tells Perl the replacement is Perl code rather
# than a text string.
示例运行
echo version=1.1.1.0 | awk'BEGIN{FS=OFS=“.”}{$NF++}1'version=1.1.1.1
@PS。我个人认为这应该是一个答案,并有适当的解释。如果我是OP:),我会接受这个答案。基本上,我需要更新文件中的版本,所以没有任何输入参数。这就是为什么我尝试使用awk查找和更新版本,而不是写回file@user6329667我又加了一个swer可以更干净地处理就地编辑。谢谢你的建议,但在这种情况下,我需要在每次脚本设置新版本时手动更新,但我需要自动更新。你说你想自动增加次要版本吗?是的,基本上我需要打开文件更改最后版本数并保存,仅此而已
perl -pe '/^version=/ and s/(\d+\.\d+\.\d+\.)(\d+)/$1 . ($2+1)/e' -i version.properties
/^version=/ and # Do the following on lines starting with `version=`
s/ # Make a replacement on those lines
(\d+\.\d+\.\d+\.)(\d+)/ # Match x.y.z.w, and set $1 = `x.y.z.` and $2 = `w`
$1 . ($2+1)/ # Replace x.y.z.w with a copy of $1, followed by w+1
e # This tells Perl the replacement is Perl code rather
# than a text string.
$ cat foo.txt
version=1.1.1.2
$ perl -pe '/^version=/ and s/(\d+\.\d+\.\d+\.)(\d+)/$1 . ($2+1)/e' -i foo.txt
$ cat foo.txt
version=1.1.1.3