gpt4 book ai didi

linux - 解析和替换两个文件中的一些字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:58 25 4
gpt4 key购买 nike

我想用这种用法运行一个 shell 脚本:

./run A.txt B.xml

A.txt 包含一些统计信息:

Accesses = 1
Hits = 2
Misses = 3
Evictions = 4
Retries = 5

B.xml 看起来像:

<stat name="total_accesses" value="0"/>
<stat name="total_misses" value="0"/>
<stat name="conflicts" value="0"/>

我想从 A.txt 中替换 B.xml 中的一些统计信息。例如,我想

1- find "Accesses" in A.txt
2- find "total_accesses" in B.xml
3- replace 0 with 1
1- find "Misses" in A.txt
2- find "total_misses" in B.xml
3- replace 0 with 3

所以 B.xml 看起来像:

<stat name="total_accesses" value="1"/>
<stat name="total_misses" value="3"/>
<stat name="conflicts" value="0"/>

我想用 shell“sed”命令来做到这一点。但是我发现它非常复杂,因为正则表达式很难理解。

“sed”是否可以帮助我解决这个问题,还是我必须找到另一种方法?

最佳答案

对于这样一个简单的案例来说,它可能有点重量级,但这里有一个 Python 脚本可以完成这项工作:

#!/usr/bin/env python
import sys
import xml.etree.ElementTree as etree

# read A.txt; fill stats
stats = {}
for line in open(sys.argv[1]):
if line.strip():
name, _, count = line.partition('=')
stats["total_"+name.lower().strip()] = count.strip()

# read B.xml; fix to make it a valid xml; replace stat[@value]
root = etree.fromstring("<root>%s</root>" % open(sys.argv[2]).read())
for s in root:
if s.get('name') in stats:
s.set('value', stats[s.get('name')])
print etree.tostring(s),

例子

$ python fill-xml-template.py A.txt B.xml 
<stat name="total_accesses" value="1" />
<stat name="total_misses" value="3" />
<stat name="conflicts" value="0" />

要增量处理输入文件或就地进行更改,您可以使用以下方法:

#!/usr/bin/env python
import fileinput
import sys
import xml.etree.ElementTree as etree

try: sys.argv.remove('-i')
except ValueError:
inplace = False
else: inplace = True # make changes inplace if `-i` option is specified

# read A.txt; fill stats
stats = {}
for line in open(sys.argv.pop(1)):
if line.strip():
name, _, count = line.partition('=')
stats["total_"+name.lower().strip()] = count.strip()

# read input; replace stat[@value]
for line in fileinput.input(inplace=inplace):
s = etree.fromstring(line)
if s.get('name') in stats:
s.set('value', stats[s.get('name')])
print etree.tostring(s)

例子

$ python fill-xml-template.py A.txt B.xml -i

它可以从标准输入读取或处理多个文件:

$ cat B.xml | python fill-xml-template.py A.txt
<stat name="total_accesses" value="1" />
<stat name="total_misses" value="3" />
<stat name="conflicts" value="0" />

关于linux - 解析和替换两个文件中的一些字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8021602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com