简体   繁体   English

Bash 脚本:如何从文件文件中读取变量内容并将其递增 +1

[英]Bash script: how do I read a variable content from file file and increment it +1

I'm writing an basic bash script where I'm reading a file which contains initially "1" as content.我正在编写一个基本的 bash 脚本,其中我正在读取一个最初包含“1”作为内容的文件。 After reading it I want to increase it +1 everytime whenever I run the script.阅读后,我想在每次运行脚本时将其增加 +1。

Example file: 1.txt示例文件:1.txt

1

Initial Content: 1初始内容:1

Expected output when run first time: 1.txt第一次运行时预期的 output:1.txt

2

Here is my script这是我的脚本

#!/misc/acc-archive/util/bash

i=$(<1.txt)

echo "$1"

j=$((i+=1))

echo "$1"

find . -exec perl -pi -e 's/$1/$j/g' 1.txt \;

You made a few mistakes.你犯了几个错误。 Here is a working copy:这是一个工作副本:

i=$(cat 1.txt)

echo "i: $i"

j=$((i+=1))

echo "j: $j"
echo "$j" > 1.txt

I changed:我变了:

  • $1 to $i $1 到 $i
  • switched from < to cat从 < 切换到 cat
  • replaced the find/perl combination with just a >仅用 > 替换了 find/perl 组合

If you're replacing the entire contents of the file:如果要替换文件的全部内容:

#!/bin/bash

i=$(<1.txt)
echo "$((++i))" > 1.txt

If you need to edit numbers in place in multiple files, you should provide more specific details about your task.如果您需要在多个文件中编辑数字,您应该提供有关您的任务的更具体的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM