搜索关键字的Python以fi开头并替换

2024-06-24 12:55:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有file1.txt,它有以下内容

if [ "x${GRUB_DEVICE_UUID}" = "x" ] || [ "x${GRUB_DISABLE_LINUX_UUID}" = "xtrue" ] \
   || ! test -e "/dev/disk/by-uuid/${GRUB_DEVICE_UUID}" \
   || uses_abstraction "${GRUB_DEVICE}" lvm; then
   LINUX_ROOT_DEVICE=${GRUB_DEVICE}
else
   LINUX_ROOT_DEVICE=UUID=${GRUB_DEVICE_UUID}
fi

GRUBFS="`${grub_probe} --device ${GRUB_DEVICE} --target=fs 2>/dev/null || true`"
Linux_CMDLINE="nowatchdog rcupdate.rcu_cpu_stall_suppress=1"

我想找到以Linux\u CMDLINE=“开始的字符串,并用Linux\u CMDLINE=”替换该行

我尝试了下面的代码,它不工作。我也认为这不是最好的执行方式。有什么简单的方法可以做到这一点吗?你知道吗

with open ('/etc/grub.d/42_sgi', 'r') as f:
    newlines = []
    for line in f.readlines():
        if line.startswith('Linux_CMDLINE=\"'):
            newlines.append("Linux_CMDLINE=\"\"")
        else:
            newlines.append(line)

with open ('/etc/grub.d/42_sgi', 'w') as f:
    for line in newlines:
        f.write(line)

预期输出:

 if [ "x${GRUB_DEVICE_UUID}" = "x" ] || [ "x${GRUB_DISABLE_LINUX_UUID}" = "xtrue" ] \
   || ! test -e "/dev/disk/by-uuid/${GRUB_DEVICE_UUID}" \
   || uses_abstraction "${GRUB_DEVICE}" lvm; then
   LINUX_ROOT_DEVICE=${GRUB_DEVICE}
else
   LINUX_ROOT_DEVICE=UUID=${GRUB_DEVICE_UUID}
fi

GRUBFS="`${grub_probe} --device ${GRUB_DEVICE} --target=fs 2>/dev/null || true`"
Linux_CMDLINE=""

Tags: devifuuidlinuxdevicelinerootelse
2条回答

由于open file for both reading and writing?,代码最少

# Read and write (r+)
with open("file.txt","r+") as f:
    find = r'Linux_CMDLINE="'
    changeto = r'Linux_CMDLINE=""'
    # splitlines to list and glue them back with join
    newstring = ''.join([i if not i.startswith(find) else changeto for i in f])
    f.seek(0)
    f.write(newstring)
    f.truncate()
repl = 'Linux_CMDLINE=""'

with open ('/etc/grub.d/42_sgi', 'r') as f:
    newlines = []
    for line in f.readlines():
        if line.startswith('Linux_CMDLINE='):
            line = repl
        newlines.append(line)

相关问题 更多 >