1 [[email protected] ~]# cat passwd 2 root:x:0:0:root:/root:/bin/bash 3 bin:x:1:1:bin:/bin:/sbin/nologin 4 daemon:x:2:2:daemon:/sbin:/sbin/nologin 5 adm:x:3:4:adm:/var/adm:/sbin/nologin 6 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 7 sync:x:5:0:sync:/sbin:/bin/sync 8 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown 9 halt:x:7:0:halt:/sbin:/sbin/halt 10 [[email protected] ~]# 11 [[email protected] ~]# python 5.py passwd 0 1 12 [[email protected] ~]# 13 [[email protected] ~]# cat passwd 14 root:x:1:1:root:/root:/bin/bash 15 bin:x:1:1:bin:/bin:/sbin/nologin 16 daemon:x:2:2:daemon:/sbin:/sbin/nologin 17 adm:x:3:4:adm:/var/adm:/sbin/nologin 18 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 19 sync:x:5:1:sync:/sbin:/bin/sync 20 shutdown:x:6:1:shutdown:/sbin:/sbin/shutdown 21 halt:x:7:1:halt:/sbin:/sbin/halt 22 [[email protected] ~]# 23 [[email protected] ~]# python 5.py passwd 1 2 passwd.new 24 [[email protected] ~]# 25 [[email protected] ~]# cat passwd 26 root:x:1:1:root:/root:/bin/bash 27 bin:x:1:1:bin:/bin:/sbin/nologin 28 daemon:x:2:2:daemon:/sbin:/sbin/nologin 29 adm:x:3:4:adm:/var/adm:/sbin/nologin 30 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 31 sync:x:5:1:sync:/sbin:/bin/sync 32 shutdown:x:6:1:shutdown:/sbin:/sbin/shutdown 33 halt:x:7:1:halt:/sbin:/sbin/halt 34 [[email protected] ~]# 35 [[email protected] ~]# cat passwd.new 36 root:x:2:2:root:/root:/bin/bash 37 bin:x:2:2:bin:/bin:/sbin/nologin 38 daemon:x:2:2:daemon:/sbin:/sbin/nologin 39 adm:x:3:4:adm:/var/adm:/sbin/nologin 40 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 41 sync:x:5:2:sync:/sbin:/bin/sync 42 shutdown:x:6:2:shutdown:/sbin:/sbin/shutdown 43 halt:x:7:2:halt:/sbin:/sbin/halt 44 [[email protected] ~]# 45 [[email protected] ~]# python 5.py passwd o 46 参数错误:python 5.py 需要编辑的文件 被替换的字符串 提成成的字符串 [另存成的文件] 47 [[email protected] ~]# python 5.py passw 1 2 48 文件不存在 49 [[email protected] ~]#
脚本代码如下:
1 #!/usr/bin/python 2 # -*- coding=UTF-8 -*- 3 4 import sys 5 import os 6 7 len_argv=len(sys.argv) 8 #print ‘传参数量‘,len_argv-1 9 10 if len_argv < 4: 11 print ‘参数错误:python ‘+sys.argv[0]+‘ 需要编辑的文件 被替换的字符串 提成成的字符串 [另存成的文件]‘ 12 13 elif len_argv > 5: 14 print ‘参数错误:python ‘+sys.argv[0]+‘ 需要编辑的文件 被替换的字符串 提成成的字符串 [另存成的文件]‘ 15 16 else: 17 if not os.path.isfile(sys.argv[1]): 18 print ‘文件不存在‘ 19 sys.exit() 20 s_file = file(sys.argv[1],‘r+‘) 21 old_str = sys.argv[2] 22 new_str = sys.argv[3] 23 d_file = file(sys.argv[1]+‘.tmp‘,‘w‘) 24 for line in s_file.readlines(): 25 d_file.writelines(line.replace(old_str,new_str)) 26 s_file.close() 27 d_file.close() 28 29 if len_argv == 4: 30 os.rename(sys.argv[1]+‘.tmp‘,sys.argv[1]) 31 else: 32 os.rename(sys.argv[1]+‘.tmp‘,sys.argv[4])
时间: 2024-10-12 15:48:59