多个 TXT 文件中的小数点加 100

多个 TXT 文件中的小数点加 100

我对此感到困惑,所以需要一些帮助。我在一个文件夹中有多个txt文件。这些文本文件中有一些内容。现在有一个文本"moveLimit":30,(逗号在小数点后面)。那么我如何将100多个文件中的所有移动小数添加并保存它们。移动不是30,它是每个文本文件中的随机数。它们都在10-999之间。

样本

{"gameModeName":"Classic moves","moveLimit":106,"numberOfColours":6,"portals":[],"protocolVersion":"0.3","randomConfig":{"mode":"Seed Pool","modeModifier":"Tutorial Only","overrideAbTest":true,"seedPool":[547787]},"randomSeed":1088126,"scoreTargets":[300,400,500],"tileMap":[["000","000","000","000","000","000","000","000","000"],["000","000","000","000","000","000","000","000","000"],["002005","002005","002005","002005","002005","002005","002005","002005","000"],["002","002","002","002","002","002","002","002","000"],["002","002","002","002","002","002","002","002","000"],["002","002","002","002","002","002","002","002","000"],["002","002","002","002","002","002","002","002","000"],["000","000","000","000","000","000","000","000","000"],["000","000","000","000","000","000","000","000","000"]]}

答案1

如果您一开始就说您的txt文件实际上是 JSON 文件(正如您的示例所示) - 它会改变一切并阻止大多数问题/评论。

使用适当的 JSON 工具,jq因为这将是正确的方法:

for f in *.txt; do
    if grep -q '"moveLimit":[0-9]*,' "$f"; then
        jq -c '.moveLimit |= . + 100' "$f" > tmp_f && mv tmp_f "$f"
    fi
done

答案2

在 GNU 或 FreeBSD 系统上,您可以尝试以下操作:

grep  -rl --null '"moveLimit":[0-9]' . |
  xargs -r0 perl -pi -e 's/"moveLimit":\K\d+/$& + 100/ge'
  • grep r递归地列出当前目录 ( ) 中包含后跟十进制数字 ( -delimited for )l的文件."moveLimit":nullxargs -0
  • xargs -r0将该文件列表传递给perl
  • perl编辑文件in 位并替换数字序列(\d+后面带有"moveLimit":相同的数字 ( $&) 加 100。

相关内容