简体   繁体   English

用于搜索关键字的Python开头并在文件中替换

[英]Python to search keyword starts with and Replace in file

I have file1.txt which has below contents 我有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"

I want to find string starts with Linux_CMDLINE=" and replace that line with Linux_CMDLINE="" 我想找到以Linux_CMDLINE =“开头的字符串,并将该行替换为Linux_CMDLINE =”“

I tried below code and it is not working. 我试过下面的代码,它不起作用。 Also I am thinking it is not best way to implement. 我也认为这不是最佳的实施方法。 Is there any easy method to achieve this? 有没有简单的方法可以做到这一点?

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)

output expected: 预期输出:

 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=""
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)

Minimal code thanks to 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()

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

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