首页 > 解决方案 > 用于搜索目录并查找以子字符串结尾的所有字符串的 Python 脚本

问题描述

我正在尝试编写一个 Python 脚本来搜索目录中的所有文件并枚举所有以子字符串“_updated”结尾的字符串。例如,如果我的文件是

// file 1
this is an_updated example file_updated
// file 2
another file here_updated

我希望我的脚本返回:

an_updated
file_updated
here_updated

到目前为止,我编写了以下脚本,用于grep查找所有包含字符串的文件。我怎样才能修改或扩展它以获得我想要的结果?grep甚至是正确的方法吗?

#!/bin/bash
files=$(find docs -name "*.txt" -exec grep -l '_updated' {} \;)

标签: pythonstringbashgrep

解决方案


from os import listdir
dirlist = list(filter(lambda x: x.endswith('_updated', listdir())))

for i in dirlist:
    print(i)

这将打印你想要的东西


推荐阅读