在文件python中查找并替换字符串

时间:2017-06-30 09:01:58

标签: python python-2.7

命令outpt:

   veera:~ # blkid
   /dev/sda1: UUID="41b8736f-5a43-4938-8b38-8df62fba50d7" TYPE="swap"
   /dev/sda2: UUID="3717cca6-cbb7-4763-a935-6e01dfa1f83c" TYPE="ext3"

  file output:
  veera:~ # cat /etc/fstab
  /dev/sda1            swap                 swap       defaults              0 0
  /dev/sda2            /                    ext3       acl,user_xattr        1 1

任何人都可以帮助我们如何在文件/ etc / fstab中将/ dev / sda1替换为uuid。

文件替换后,它应如下所示:

veera:~ # cat /etc/fstab
UUID=41b8736f-5a43-4938-8b38-8df62fba50d7            swap                 swap       defaults              0 0
UUID=3717cca6-cbb7-4763-a935-6e01dfa1f83c            /                    ext3       acl,user_xattr        1 1

2 个答案:

答案 0 :(得分:0)

我编写代码来根据问题要求替换字符串。

请验证并让我知道是否有更好的方法来实现这一目标

import subprocess
proc = subprocess.Popen('blkid', stdout=subprocess.PIPE)
tmp = proc.stdout.read()

d = {}
for line in tmp.split("\n"):
        if ":" not in line:
                continue
        key,value = line.strip().split(":", 1)
        d[key] = value
with open('/etc/fstab', 'r') as file:
        filedata = file.read()
for k, v in d.iteritems():
        for line in filedata.split("\n"):
                if k in line:
                        data = v.strip().split(" ")
                        data = data[0].replace("\"","")
                        filedata = filedata.replace(k, data)
with open('/etc/fstab', 'w') as file:
        file.write(filedata)

答案 1 :(得分:0)

在Linux操作系统上,使用 awk 工具单行

awk -F' |: ' 'NR==FNR{ a[$1]=$2; next } $1 in a { $1=a[$1]; print }' <(blkid) /etc/fstab

输出:

UUID="41b8736f-5a43-4938-8b38-8df62fba50d7"            swap                 swap       defaults              0 0
UUID="3717cca6-cbb7-4763-a935-6e01dfa1f83c"            /                    ext3       acl,user_xattr        1 1