grep用法和范例

grep 最基本的用法

grep keyword file1 file2

在 /etc/os-release 查询 Ubuntu

grep Ubuntu /etc/os-release

NAME="Ubuntu"
PRETTY_NAME="Ubuntu 18.04.4 LTS"

在 /etc/*.conf 中查询network 关键字

grep network /etc/*.conf

/etc/appstream.conf:# over data provided from a network source .
/etc/ffserver.conf:# several network interfaces.
/etc/ffserver.conf:# 'ACL deny 1.0.0.0 1.255.255.255' would deny the whole of network 1 and
/etc/ltrace.conf:hex(uint) inet_network(string );
/etc/nsswitch.conf:networks: fi les
/etc/sysctl.conf:# Additional settings - these settings can improve the network
/etc/sysctl.conf:# security of the host and prevent against some network attacks
/etc/sysctl.conf:# redirection. Some network environments, however, require that these

搭配管道pipe

ls /etc/ | grep network

network
networkd-dispatcher
networks

不区分大小写: -i

# 不分大小写
grep -i Ubuntu /etc/os-release

显示行号: -n

grep -n Ubuntu /etc/os-release

1:NAME="Ubuntu"
5:PRETTY_NAME="Ubuntu 18.04.4 LTS"

反相匹配:-v

# 过滤不包含Ubuntu的行
grep -v Ubuntu /etc/os-release

文件夹递归所有文件:-r

grep -r ubuntu /etc/

递归匹配特定的文件: --include

# 在所有 *.conf 中查询 ubuntu
grep -r --include="*.conf" ubuntu /etc/

权限错误讯息导向 /dev/null,只看正常信息:2>dev/null

# 不显示错误信息
grep -r ubuntu /etc/ 2>/dev/null

显示前后几行 -A(After)、-B(Before)或-C(Context)

# 多显示后一行
grep -A 1 Ubuntu /etc/os-release

# 多显示前一行
grep -B 1 Ubuntu /etc/os-release

# 多显示前后各一行
grep -C 1 Ubuntu /etc/os-release

猜你喜欢

转载自www.cnblogs.com/Raymon-Geng/p/13178002.html