简体   繁体   中英

Editing a text file in linux using sed

I have created a script that "simulates" a bank system that allows the user to check their balance and withdraw or deposit money depending on their needs. Details about customer, their balance etc. are saved in a text file named data.txt. When a customer withdraws or deposits money, the text file should be adjusted accordingly. Problem is, using sed like this

sed -i 's/$balance/$($balance + $depositval)/' data.txt 

doesn't work. I tried with grep too but no luck either. Is there any way to change the customer's balance to a sum generated from their balance along with the amount of money they wish to deposit (or substract if they need to withdraw money) using sed and passing as argument a variable?

PS: Here are the contents of my data.txt file:

12345 Nick Abrams A 25575
67890 George Michaels I 10000
14680 Jack Jordan A 2960
13670 Michael Patton I 5065

The first field is the customer's card number. A and I indicate whether a customer's card is active or inactive. 5th field is balance. BTW i'm using bash shell. Depositval is read from keyboard using read command and balance is found from text file using grep.

For future reference, if somebody needs to do something similar i found out that my first attempt using sed like this

sed -i 's/$balance/$($balance + $depositval)/' data.txt

works too, just need to change the ' with "

Using a text file rather than a database is hugely inefficient because the entire file has to be rewritten for each transaction. But here are the beginnings of a solution.

awk -v deposit="123.45" -v account="14680" '$1 == account { $5 += deposit }' file >newfile &&
mv newfile file

GNU Awk has an option to rewrite the input file in-place so you don't have to do the manual moving of the new file back on top of the old one.

Here is a test case. $(( ... )) arithmetic operation is specific to bash .

$ a=1
$ b=2
$ cat data.txt
name 1

$ sed "s/$a/$(( $a + $b ))/g" data.txt
name 3

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