【问题标题】:Bash: iterate over several files and perform a different change for each fileBash:遍历多个文件并对每个文件执行不同的更改
【发布时间】:2014-04-25 23:13:16
【问题描述】:

我想在几个 txt 文件中更改一个变量。但是这个变量不应该在每个 txt 文件中都相等。 我试过了,但它不起作用。

for file in ./*.txt ;do
    for value in $(seq 1 5); do
        sed -i 's/x_max=.*/x_max='$value'/ ' $file
    done
done

所以每个 x_max 都有值:5

【问题讨论】:

  • 当然。您在每个文件上运行五个替换中的每一个。所以他们都以最后一次编辑结束。
  • 您在sed 运行之前创建一个循环,每次迭代都会递增。由于文件被覆盖,每个文件都会有x_max=5

标签: bash shell replace sed text-processing


【解决方案1】:

应该这样做 - 每次运行后只迭代一次并将计数器加 1:

counter=1

for file in ./*.txt ;do
    sed -i 's/x_max=.*/x_max='$counter'/ ' $file
    (( counter++ ))
done

【讨论】:

    【解决方案2】:

    这应该可以解决问题。每个文件只替换一次,每次使用不同的值。

    value=1
    for file in *.txt; do
      sed -i 's/x_max=.*/x_max='$value'/' $file
      value=$((value + 1))
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2017-08-21
      相关资源
      最近更新 更多