如何使用 bash 更新文件中的值?

How to update a value in a file by using bash?

我有一个包含多行的文件,需要在 "jobid" 字符串中的十六进制数上加 1:

<jobid>a3445-34729-3b34b</jobid>

我可以用sed来过滤这一行,但是如何进行十六进制计算呢? 结果值应该是这样的:

<jobid>a3445-34729-3b34c</jobid>

要进行十六进制运算,请在您的数字字符串前加上“0x”。因此,如果您已使用 sed 将您的号码提取到 $n

> n="0x"$n
> echo $n
0x3b34b
> n=$((n+1))
> echo $n
242748              # bash saves the result as a decimal string
> printf "%x\n" $n
0x3b43c             # but you can use printf to output it in hex

使用这个 script:

#!/bin/bash
last_jobid=$(grep '<jobid>.*</jobid>'  | cut -d'>' -f2 | cut -d'<' -f1 | cut -d'-' -f3)
new_jobid=$((0x$last_jobid + 1))
new_jobid=$(printf "%x\n" $new_jobid)
sed -r "s|(<jobid>[^-]+-[^-]+-)[^-]+(</jobid>)|$new_jobid|" 

到运行它:

./script job.xml