当前位置:网站首页>如何在匹配行之前使用 grep 显示文件名和行号
如何在匹配行之前使用 grep 显示文件名和行号
2022-07-29 10:52:00 【mikes zhang】

grep 是一个 Linux 实用程序,通常用于搜索文件内容或传递给它的任何输入。在搜索多个文件时,显示文件名和行号很有用,尤其是在使用它在 shell 脚本中自动化时。
使用 grep 显示文件名
默认情况下,如果您将多个文件传递给,为了清楚起见grep,它将显示filename: 在匹配行之前。您实际上可以使用标志关闭此行为,该-h 标志永远不会显示文件名:

但是,如果您只将一个文件传递给grep,则默认情况下它不会显示文件名。在使用 shell 脚本进行自动化时,这可能会成为一个问题,因为您可能不知道目录中有多少文件,并且它可能会破坏依赖于文件名的自动化。
简单的解决方法是使用大写 -H 标志,它与文件名相反,-h 并且无论如何都会打开文件名,即使只有一个文件作为输入传递。
grep -H "foo" file

该-H 标志还有另一个意想不到但有用的效果——当与来自 的输入(例如 Unix 管道)配对时stdin,它将(standard input): 代替文件名打印。
使用 grep 显示行号
您还可以将其与-n 标志结合使用以获取行号:
grep -Hn "foo"

符合 POSIX
中的-H 标志grep不符合 POSIX,并且在一些更晦涩的基于 Unix 的操作系统中不可用。幸运的是,您可以使用一个 hack,通过将/dev/null 伪造的第二个文件输入传递给grep,这会欺骗它认为有多个文件:

边栏推荐
- Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29
- 站点数据收集-Scrapy使用笔记
- Less than 10% of the 3 software test interview questions can be answered correctly! How many do you know?
- LeetCode_1049_最后一块石头的重量Ⅱ
- Review of the 16th issue of HMS core discovery | play with the new "sound" state of AI with tiger pier
- Hugo NexT V4 介绍
- Talk about the establishment of performance testing environment
- Sunwenlong, Secretary General of the open atom open source foundation, worked together to expand open source
- StarRocks 技术内幕:实时更新与极速查询如何兼得
- Matplotlib Chinese question
猜你喜欢

How to realize the function of adding watermark

Alibaba architects spent a year sorting out the "Lucene advanced document", and you are also a big factory employee!

美团、饿了么被杭州市监约谈要求落实食品安全管理责任 严禁恶意竞争

Understand what a binary tree is (types, traversal methods, definitions of binary trees)

PHP basics uses arrays to save data

Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29

一键搭建博客:如何使用WordPress插件搭建专属博客

Discussion on the application of arcing smart electricity in elderly care institutions

周鸿祎:360是世界上最大的安全大数据公司

Kunlun storage vs PostgreSQL OLTP test
随机推荐
通过tidymodels使用XGBOOST
『知识集锦』一文搞懂mysql索引!!(建议收藏)
Pytorch 入门
Software testing dry goods
1.MySQL数据库的介绍
Factoextra: visual PCA of multivariate statistical methods
2.安装MySQL
️ 炒 股 实 战丨原 地 起 飞 ️
为什么应该在开发环境中使用 Kubernetes
报表控件FastReport与StimulSoft功能对比
重磅 | 基金会为白金、黄金、白银捐赠人授牌
How to realize the function of adding watermark
ggdag 绘制DAG和因果图
Spark efficient data analysis 02, basic knowledge 13
R language brca MRNA data set analysis
Svn revision keyword
LeetCode_1049_最后一块石头的重量Ⅱ
AI模型风险评估 第2部分:核心内容
Watch the open source summit first | quick view of the sub Forum & Activity agenda on July 29
LeetCode二叉树系列——144.二叉树的前序遍历