仅使用 Linux shell 匹配字符串并打印行号
这是一个关于如何搜索文件的简单示例,我们只打印匹配字符串的行号,而不是将匹配字符串打印到 STOUT。例如,考虑以下文件:
$ nl test.txt
1 linux
2 bash
3 shell
4 power
5 linux
6 shell
7 command
8 GNU
首先使用 -n 选项打印匹配字符串 shell 的行号:
$ grep -n shell test.txt
3:shell
6:shell
最后一步将 STDOUT 通过管道传输到 cut 命令:
$ grep -n shell test.txt | cut -d : -f1
3
6
如果您需要在一行上输出,请在 tr 命令中再添加一个管道,以删除所有换行符并将其替换为单个空格:
grep -n shell test.txt | cut -d : -f1 | tr "\n" " "
3 6
