问题描述
我想在文本文件中搜索包含特定字符串的行。
例如,我搜索的行包含字符串umask 022
,而不是/etc/profile
文件中的行注释。
我的代码:
def check_umask(fname, umask):
with open(fname) as f:
return any(umask in line for line in f)
check_umask('/etc/profile','umask 022')
使用上面的代码,但它显示行注释:
# .....
# By default, we want ... umask 022
# bla..bla... umask 022
.........
umask 022
那么,如何仅显示包含umask 022
脚本的行,而不显示行注释?
1楼
您可以使用strip
和startswith
的组合。
def check_umask(fname, umask):
with open(fname) as f:
for line in f:
if not line.strip().startswith('#') and 'umask 022' in line:
print line
check_umask('/etc/profile','umask 022')
例子:
>>> s = '''# .....
# By default, we want ... umask 022
# bla..bla... umask 022
.........
umask 022'''.splitlines()
>>> for line in s:
if not line.strip().startswith('#') and 'umask 022' in line:
print line
umask 022
>>>
或者
for line in s:
if re.search(r'^[^#]*umask 022', line):
print line
2楼
mo = re.search(r'[^#]*umask 022', line)
if mo:
print(mo.group())
3楼
您可以使用str.find()
来比较索引。
如果未找到匹配项,则返回 -1,因此我们可以通过加 1 将其转换为真/假值:
for line in content:
p = line.find('#') + 1
u = line.find('umask 022') + 1
if u and (not p or p > u):
print(line)
4楼
我的案子又遇到了其他问题。 在“#”之前是一个有效的命令。
export PATH=$PATH:/... # umask 022
所以,@Raj 的脚本仍然显示这一行,尽管它在注释中包含“umask 022”。 那么,我们有解决方案吗???