awk - 让 grep 显示带有前导零、前导空格或填充的行号

标签 awk grep

grep -n ... 在每行前面加上行号。但格式可能会使输出难以人类解释:

$ grep -n hello hello.txt
1:hello my dear
5:hello in another line
17:this is a hello in a two-digits line number
20:another hello in the two-digits line realm
3838813:it's a long file and here comes one last hello

有没有办法让 grep 以填充方式显示行号,例如使用前导零或前导空格?

示例:

$ grep -n -$MAGIC hello hello.txt
      1:hello my dear
      5:hello in another line
     17:this is a hello in a two-digits line number
     20:another hello in the two-digits line realm
3838813:it's a long file and here comes one last hello

最佳答案

不,没有办法仅使用 grep 来完成您想要的操作,而是将 grep 输出传输到 awk 等其他工具进行格式化,为什么不使用 awk,例如:

awk '/hello/{printf "%10d:%s\n", FNR, $0}' hello.txt

例如空白填充:

$ seq 30 | awk '/5/{printf "%10d:%s\n", FNR, $0}'
         5:5
        15:15
        25:25

或零填充:

$ seq 30 | awk '/5/{printf "%010d:%s\n", FNR, $0}'
0000000005:5
0000000015:15
0000000025:25

如果 10 不足以容纳可能的行号,则选择一个更大的数字,或者如果您想计算字段宽度,则可以缓冲匹配,例如 @RavinderSing13 shows in their answer 。当然,还有内存和执行速度,但这实际上不应该成为问题,除非您在输入中确实有数十亿个正则表达式匹配。

关于awk - 让 grep 显示带有前导零、前导空格或填充的行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67253340/

相关文章:

unix - 将第一列的重复值替换为字符“

awk - 如何仅从每一列的一行中的第一个单词中删除特定字符?

linux - 在多个文件中搜索文本文件中的单词列表

python - 如何使用 awk 或 grep 在日志文件中捕获整个 Python 回溯?

linux - 如何使用 "awk"执行具有相同尾部的多个文件并导出到一些具有新尾部的新文件?

regex - 使用 sed 时的多个条件

linux - 在awk中设置一个外部变量

awk - 匹配特定列的 grep 文件

regex - awk 模式匹配和允许一个歧义/不匹配的解决方案

grep 与 string1 或 string2 匹配