简体   繁体   中英

Python to search keyword starts with and Replace in file

I have file1.txt which has below contents

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

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()

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