简体   繁体   English

使用sed在Linux中编辑文本文件

[英]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. 有关客户及其余额等的详细信息保存在名为data.txt的文本文件中。 When a customer withdraws or deposits money, the text file should be adjusted accordingly. 当客户提款或存款时,应相应调整文本文件。 Problem is, using sed like this 问题是,像这样使用sed

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

doesn't work. 不起作用。 I tried with grep too but no luck either. 我也尝试过grep,但也没有运气。 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? 是否有任何方法可以使用sed并将变量作为参数传递,将客户的余额更改为从其余额以及他们希望存入的金额(或如果需要提取资金,则减去)的总金额?

PS: Here are the contents of my data.txt file: PS:这是我的data.txt文件的内容:

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. A和I指示客户的卡有效还是无效。 5th field is balance. 第五场是平衡。 BTW i'm using bash shell. 顺便说一句,我正在使用bash shell。 Depositval is read from keyboard using read command and balance is found from text file using grep. 使用读取命令从键盘读取Depositval,并使用grep从文本文件中找到余额。

For future reference, if somebody needs to do something similar i found out that my first attempt using sed like this 供以后参考,如果有人需要做类似的事情,我发现我第一次尝试使用sed是这样的

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. GNU Awk可以选择就地重写输入文件,因此您不必手动将新文件移回旧文件。

Here is a test case. 这是一个测试案例。 $(( ... )) arithmetic operation is specific to bash . $(( ... ))算术运算特定于bash

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

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

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

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