Bash技巧:如何判断一个文件的行是否是另一文件行的子串?
搞定文本匹配输出的两种方案
嘿,这就给你解决这个文本筛选和输出的问题!先理清楚咱们的文件和需求:
咱们的文件内容
- 1.txt(基础路径列表):
/stackoverflow.com/questions /stackoverflow.com/reports /stackoverflow.com/answers
- 2.txt(详细路径列表):
/stackoverflow.com/questions/18959800/grep-each-line-from-a-file-in-another-file /stackoverflow.com/answers/18984800/grep-each-line-from /stackoverflow.com/questions/20559800/line-from-a-file-in-another-file /stackoverflow.com/ask/9959800/file-in-another-file-second_line
需求拆解
咱们要实现两个核心逻辑:
- 输出1.txt里的所有行(看你给的示例,哪怕像
/stackoverflow.com/reports这种没在2.txt里找到对应行的也需要保留) - 输出2.txt里没匹配到1.txt任何行的内容
同时你也接受另一种更直接的形式:合并两个文件的所有行输出。
方案一:输出1.txt全量 + 2.txt未匹配行
用命令行工具就能轻松实现,直接运行下面的命令就能生成你要的第一种output.txt:
{ cat 1.txt; grep -v -f <(sed 's/^/^/' 1.txt) 2.txt; } > output.txt
这个命令的逻辑是:
- 先把1.txt的所有内容输出
- 再用
grep筛选出2.txt里不包含1.txt任何行开头的内容(sed 's/^/^/'是给1.txt的每行加开头锚定,确保是路径前缀匹配) - 最后把结果写入
output.txt
生成的结果就是你期望的:
/stackoverflow.com/questions /stackoverflow.com/reports /stackoverflow.com/answers /stackoverflow.com/ask/9959800/file-in-another-file-second_line
方案二:直接合并所有行输出
如果是要第二种合并所有行的形式,那就更简单了,直接把两个文件内容拼接就行:
cat 1.txt 2.txt > output.txt
得到的结果就是:
/stackoverflow.com/questions /stackoverflow.com/reports /stackoverflow.com/answers /stackoverflow.com/questions/18959800/grep-each-line-from-a-file-in-another-file /stackoverflow.com/answers/18984800/grep-each-line-from /stackoverflow.com/questions/20559800/line-from-a-file-in-another-file /stackoverflow.com/ask/9959800/file-in-another-file-second_line
内容的提问来源于stack exchange,提问作者nowens
相关产品推荐
相关产品推荐

