perl grep 命令全部示范
时间: 2023-09-18 19:10:35 浏览: 40
Perl中的grep命令可以用于从文件或标准输入中过滤出符合条件的行。下面是一些常见的示例:
1. 过滤出包含特定字符串的行
```
# 从文件中过滤出包含"hello"的行
grep 'hello' file.txt
# 从标准输入中过滤出包含"world"的行
echo "hello world" | grep 'world'
```
2. 过滤出不包含特定字符串的行
```
# 从文件中过滤出不包含"hello"的行
grep -v 'hello' file.txt
# 从标准输入中过滤出不包含"world"的行
echo "hello world" | grep -v 'world'
```
3. 过滤出匹配正则表达式的行
```
# 从文件中过滤出匹配"^[A-Z]"的行(以大写字母开头)
grep -E '^[A-Z]' file.txt
# 从标准输入中过滤出匹配"\d+"的行(包含数字)
echo "1a 2b 3c" | grep -E '\d+'
```
4. 过滤出不匹配正则表达式的行
```
# 从文件中过滤出不匹配"^[A-Z]"的行(不以大写字母开头)
grep -Ev '^[A-Z]' file.txt
# 从标准输入中过滤出不匹配"\d+"的行(不包含数字)
echo "1a 2b 3c" | grep -Ev '\d+'
```
5. 显示匹配行的行号
```
# 从文件中过滤出包含"hello"的行,并显示行号
grep -n 'hello' file.txt
# 从标准输入中过滤出包含"world"的行,并显示行号
echo "hello world" | grep -n 'world'
```
6. 显示匹配行之前或之后的多少行
```
# 从文件中过滤出"hello"所在的行及其之前的2行
grep -B 2 'hello' file.txt
# 从文件中过滤出"hello"所在的行及其之后的3行
grep -A 3 'hello' file.txt
```
7. 统计匹配行的数量
```
# 统计文件中包含"hello"的行数
grep -c 'hello' file.txt
# 统计标准输入中包含"world"的行数
echo "hello world" | grep -c 'world'
```
8. 从多个文件中过滤出匹配行
```
# 从file1.txt和file2.txt中过滤出包含"hello"的行
grep 'hello' file1.txt file2.txt
# 从当前目录下所有txt文件中过滤出包含"world"的行
grep 'world' *.txt
```