我有一个以下字符串值,我想增加字符串中的索引,如下所示。
{
"name": "poc_param_model_001",
"type": "DOUBLE",
"role": "MEASURE",
"seq": 1
}
这就是我想做的。
{
"name": "poc_param_model_002",
"type": "DOUBLE",
"role": "MEASURE",
"seq": 2
}
{
"name": "poc_param_model_003",
"type": "DOUBLE",
"role": "MEASURE",
"seq": 3
}
{
"name": "poc_param_model_004",
"type": "DOUBLE",
"role": "MEASURE",
"seq": 4
}
....
{
"name": "poc_param_model_099",
"type": "DOUBLE",
"role": "MEASURE",
"seq": 99
}
如何实现这个场景呢?
答案1
假设您的数据存储在 data.txt 中,您可以使用以下内容:
while IFS= read -r line
do
if grep -q "^ *\"seq\" *: *[^ ]\+ *\$" <<< "$line"; then
prefix=$(sed -E "s/^( *\"seq\" *: *)[^ ]+ *\$/\1/" <<< "$line" )
number=$(sed -E "s/^ *\"seq\" *: *([^ ]+) *\$/\1/" <<< "$line" )
suffix=$(sed -E "s/^ *\"seq\" *: *[^ ]+( *)\$/\1/" <<< "$line" )
echo "$prefix$((++number))$suffix"
else
echo "$line"
fi
done < data.txt
该脚本读取所有数据,找到“seq”:并递增其后面的数字