简体   繁体   中英

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. After reading it I want to increase it +1 everytime whenever I run the script.

Example file: 1.txt

1

Initial Content: 1

Expected output when run first time: 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
  • switched from < to cat
  • replaced the find/perl combination with just a >

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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