如何清除呢? 如果你的配置文件中,不使用汉字,可以用一个命令搞定:
tr -c ' [:print:]' ' ' < /usr/local/apache/conf/httpd.conf > /tmp/newhttpd.conf
第一字符集,包括了换行、回车、制表符、可打印字符,这些需要保护,其它的,全换成空格了
tr (选项) (参数) 选项 -c或——complerment:取代所有不属于第一字符集的字符; -d或——delete:删除所有属于第一字符集的字符; -s或--squeeze-repeats:把连续重复的字符以单独一个字符表示; -t或--truncate-set1:先删除第一字符集较第二字符集多出的字符。 参数 •字符集1:指定要转换或删除的原字符集。当执行转换操作时,必须使用参数“字符集2”指定转换的目标字符集。但执行删除操作时,不需要参数“字符集2”; •字符集2:指定要转换成的目标字符集。 例子,将制表符替换成空格: cat filename | tr ' ' ' '
如果希望能保留中文注解,需要一些复杂的代码,考虑到linux bash shell 脚本 晦涩又长的丑,决定用优雅的python来写。下列代码就是清除.conf文件中非打印字符,但注解部分不处理,用法如下:
python scanconf.py -c /usr/local/apache/conf/httpd.conf
代码如下 :
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 """ 4 __title__ = '扫描并清除linux配置文件 .conf 中的非打印字符(#注解后面的除外)' 5 __author__ = 'shen.bas' 6 __date__ = '2017/12/3' 7 # python scanconf.py -s /usr/local/apache/conf/httpd.conf 8 """ 9 import os, sys 10 import platform 11 from io import open 12 import string 13 14 class Scaner(object): 15 16 def __init__(self,conf_filepath): 17 self.conf_file = conf_filepath 18 19 def scan(self,is_clean): 20 with open(self.conf_file, "rt", encoding="utf-8") as f:#linux default format 21 newlines = '' 22 lines = f.readlines() 23 line_no = 1 24 for line in lines: 25 sp = line.split('#') 26 conf_str = sp[0] 27 memo_str ='' 28 for s in sp[1:]: 29 memo_str += '#' + s #有多少都串联起来 30 conf_filter_list = filter(lambda x:x in string.printable,list(conf_str)) 31 conf_filter_str = ''.join(conf_filter_list) # list to str 32 newline = conf_filter_str + memo_str 33 newlines += newline + ' ' 34 if len(line) != len(newline): #说明过滤掉了些垃圾 35 print('err_row %d: %s'%(line_no,line)) 36 line_no = line_no+1 37 38 if is_clean: 39 with open(self.conf_file, "wt", encoding="utf-8") as f: 40 f.write(newlines) 41 42 43 def check_argv_ok(): 44 if len(sys.argv) < 3: 45 print(' scanconf [options] conf_file_name -s : only scan for error. -c : scan and clean error. ') 46 return False 47 else: 48 return True 49 50 def check_platform_ok(): 51 my_os = platform.platform() 52 if (my_os.find('Linux') > -1): 53 return True 54 else: 55 print('run only for linux') 56 return False 57 58 if __name__ == '__main__': 59 if check_platform_ok() and check_argv_ok(): 60 s = Scaner(sys.argv[2]) 61 if sys.argv[1] == '-s': 62 s.scan(False) 63 elif sys.argv[1] == '-c': 64 s.scan(True) 65 else: 66 print(' [options] must be -s or -c ')
开始准备用cat -A 方式处理,所以限制在linux中运行,后来发现不是个简单主意,改成直接过滤了,因此也可以运行在windows平台,懒得动了,需要自己改改就行。