Linux: grep command

本文深入解析了Unix系统中的Grep命令,包括其语法、基本使用、高级搜索技巧、特殊选项和输出格式等内容。通过一系列具体实例,帮助用户熟练掌握Grep的强大功能,提高文本处理效率。

About grep

grep prints lines of input matching a specified pattern.


grep command Syntax

grep [OPTIONS] PATTERN [FILE...]

Description

grep searches the named input FILEs (or standard input if no files are named, or if a single dash (“-“) is given as the file name) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.
In addition, three variant programs egrep, fgrep and rgrep are available:
egrep is the same as grep -E.
fgrep is the same as grep -F.
rgrep is the same as grep -r.
Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified.


Examples

First create the following demo_file that will be used in the examples below to demonstrate grep command.

$ cat demo_file

THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.

Two lines above this line is empty.
And this is the last line.

Search for the given string in a single file

The basic usage of grep command is to search for a specific string in the specified file as shown below.
Syntax:
grep “literal_string” filename

$ grep "this" demo_file

this line is the 1st lower case line in this file.
Two lines above this line is empty.

Checking for the given string in multiple files.

Syntax:
grep “string” FILE_PATTERN

This is also a basic usage of grep command. For this example, let us copy the demo_file to demo_file1. The grep output will also include the file name in front of the line that matched the specific pattern as shown below. When the Linux shell sees the meta character, it does the expansion and gives all the files as input to grep.

$ cp demo_file demo_file1

$ grep "this" demo_*

demo_file:this line is the 1st lower case line in this file.
demo_file:Two lines above this line is empty.
demo_file:And this is the last line.
demo_file1:this line is the 1st lower case line in this file.
demo_file1:Two lines above this line is empty.
demo_file1:And this is the last line.

Case insensitive search using grep -i

Syntax:
grep -i “string” FILE

This is also a basic usage of the grep. This searches for the given string/pattern case insensitively. So it matches all the words such as “the”, “THE” and “The” case insensitively as shown below.

$ grep -i "the" demo_file

THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
And this is the last line.

Match regular expression in files

Syntax:
grep “REGEX” filename

This is a very powerful feature, if you can use use regular expression effectively. In the following example, it searches for all the pattern that starts with “lines” and ends with “empty” with anything in-between. i.e To search “lines[anything in-between]empty” in the demo_file.

$ grep "lines.*empty" demo_file

Two lines above this line is empty.

From documentation of grep: A regular expression may be followed by one of several repetition operators:
? The preceding item is optional and matched at most once.
* The preceding item will be matched zero or more times.
+ The preceding item will be matched one or more times.
{n} The preceding item is matched exactly n times.
{n,} The preceding item is matched n or more times.
{,m} The preceding item is matched at most m times.
{n,m} The preceding item is matched at least n times, but not more than m times.


Checking for full words, not for sub-strings using grep -w

If you want to search for a word, and to avoid it to match the substrings use -w option. Just doing out a normal search will show out all the lines.

The following example is the regular grep where it is searching for “is”. When you search for “is”, without any option it will show out “is”, “his”, “this” and everything which has the substring “is”.

$ grep -i "is" demo_file

THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
This Line Has All Its First Character Of The Word With Upper Case.
Two lines above this line is empty.
And this is the last line.

The following example is the WORD grep where it is searching only for the word “is”. Please note that this output does not contain the line “This Line Has All Its First Character Of The Word With Upper Case”, even though “is” is there in the “This”, as the following is looking only for the word “is” and not for “this”.

$ grep -iw "is" demo_file

THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE.
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

Displaying lines before/after/around the match using grep -A, -B and -C

When doing a grep on a huge file, it may be useful to see some lines after the match. You might feel handy if grep can show you not only the matching lines but also the lines after/before/around the match.

Please create the following demo_text file for this example.

$ cat demo_text

4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:

 * e - go to the end of the current word.
 * E - go to the end of the current WORD.
 * b - go to the previous (before) word.
 * B - go to the previous (before) WORD.
 * w - go to the next word.
 * W - go to the next WORD.

WORD - WORD consists of a sequence of non-blank characters, separated with white space.
word - word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

 * 192.168.1.1 - single WORD
 * 192.168.1.1 - seven words.

Display N lines after match

-A is the option which prints the specified N lines after the match as shown below.
Syntax:
grep -A < N > “string” FILENAME

The following example prints the matched line, along with the 3 lines after it.

$ grep -A 3 -i "example" demo_text

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.

Display N lines before match

-B is the option which prints the specified N lines before the match.
Syntax:
grep -B < N > “string” FILENAME

When you had option to show the N lines after match, you have the -B option for the opposite.

$ grep -B 2 "single WORD" demo_text

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD

Display N lines around match

-C is the option which prints the specified N lines before the match. In some occasion you might want the match to be appeared with the lines from both the side. This options shows N lines in both the side(before & after) of match.

$ grep -C 2 "Example" demo_text
word - word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD

Highlighting the search using GREP_OPTIONS

As grep prints out lines from the file by the pattern / string you had given, if you wanted it to highlight which part matches the line, then you need to follow the following way.

When you do the following export you will get the highlighting of the matched searches. In the following example, it will highlight all the this when you set the GREP_OPTIONS environment variable as shown below.

$ export GREP_OPTIONS='--color=auto' GREP_COLOR='100;8'

$ grep this demo_file
this line is the 1st lower case line in this file.
Two lines above this line is empty.
And this is the last line.

Searching in all files recursively using grep -r

When you want to search in all the files under the current directory and its sub directory. -r option is the one which you need to use. The following example will look for the string “ramesh” in all the files in the current directory and all it’s subdirectory.

$ grep -r "ramesh" *

Invert match using grep -v

You had different options to show the lines matched, to show the lines before match, and to show the lines after match, and to highlight match. So definitely You’d also want the option -v to do invert match.

When you want to display the lines which does not matches the given string/pattern, use the option -v as shown below. This example will display all the lines that did not match the word “go”.

$ grep -v "go" demo_text
4. Vim Word Navigation

You may want to do several navigation in relation to the words, such as:

WORD - WORD consists of a sequence of non-blank characters, separated with white space.
word - word consists of a sequence of letters, digits and underscores.

Example to show the difference between WORD and word

* 192.168.1.1 - single WORD
* 192.168.1.1 - seven words.

display the lines which does not matches all the given pattern.

Syntax:
grep -v -e “pattern” -e “pattern”

$ cat test-file.txt
a
b
c
d

$ grep -v -e "a" -e "b" -e "c" test-file.txt
d

Counting the number of matches using grep -c

When you want to count that how many lines matches the given pattern/string, then use the option -c.
Syntax:
grep -c “pattern” filename

$ grep -c "go" demo_text
6

When you want do find out how many lines matches the pattern

$ grep -c this demo_file
3

When you want do find out how many lines that does not match the pattern

$ grep -v -c this demo_file
4

Display only the file names which matches the given pattern using grep -l

If you want the grep to show out only the file names which matched the given pattern, use the -l (lower-case L) option.

When you give multiple files to the grep as input, it displays the names of file which contains the text that matches the pattern, will be very handy when you try to find some notes in your whole directory structure.

$ grep -l this demo_*
demo_file
demo_file1

Show only the matched string

By default grep will show the line which matches the given pattern/string, but if you want the grep to show out only the matched string of the pattern then use the -o option.

It might not be that much useful when you give the string straight forward. But it becomes very useful when you give a regex pattern and trying to see what it matches as

$ grep -o "is.*line" demo_file
is line is the 1st lower case line
is line
is is the last line

Show the position of match in the line

When you want grep to show the position where it matches the pattern in the file, use the following options as
Syntax:
grep -o -b “pattern” file

$ cat temp-file.txt
12345
12345

$ grep -o -b "3" temp-file.txt
2:3
8:3

Note: The output of the grep command above is not the position in the line, it is byte offset of the whole file.


Show line number while displaying the output using grep -n

To show the line number of file with the line matched. It does 1-based line numbering for each file. Use -n option to utilize this feature.

$ grep -n "go" demo_text
5: * e - go to the end of the current word.
6: * E - go to the end of the current WORD.
7: * b - go to the previous (before) word.
8: * B - go to the previous (before) WORD.
9: * w - go to the next word.
10: * W - go to the next WORD.

Reference

http://www.thegeekstuff.com/2009/03/15-practical-unix-grep-command-examples/
http://www.computerhope.com/unix/ugrep.htm

<think> 我们面对的问题是:在加载`~/.bash_profile`配置文件时出现错误,包括`tty: command not found`、`grep: command not found`等基本命令找不到,以及`mmlsquota`命令报错。我们需要解决这些问题。 根据引用信息,我们可以分析原因: 1. 引用[1]表明,当执行`source /etc/profile`时,出现了基本命令(如`ls`、`vim`、`grep`)找不到的情况。这通常是因为环境变量`PATH`被错误修改,导致系统无法找到这些命令的位置。 2. 引用[2][3][4]说明了环境变量配置文件(如`/etc/profile`、`~/.bashrc`、`~/.bash_profile`)的作用和加载顺序。其中,`~/.bash_profile`在用户登录时执行一次,并且会执行`~/.bashrc`(如果存在的话)。同时,引用[3]还提到,修改`.bashrc`后需要使用`source`命令使其生效。 3. 引用[5]展示了`~/.profile`文件的内容,其中设置了`PATH`环境变量,并提到如果存在`~/.bash_profile`或`~/.bash_login`,则不会读取`~/.profile`。 因此,问题的原因可能在于: - `~/.bash_profile`中的某些命令或设置修改了`PATH`环境变量,导致系统无法找到常用命令(如`grep`、`tty`等)。 - 另外,`mmlsquota`命令报错可能是由于该命令未安装或路径未包含在`PATH`中。 解决思路: 1. 恢复`PATH`环境变量,使其包含系统命令的默认路径(如`/bin`、`/usr/bin`等)。 2. 检查`~/.bash_profile`中的设置,特别是对`PATH`的修改,确保不会覆盖系统默认路径。 3. 确保`mmlsquota`命令已正确安装,并将其所在路径添加到`PATH`中(如果不在默认路径)。 具体步骤: **步骤1:临时恢复PATH** 由于当前环境命令找不到,我们需要先临时设置一个可用的PATH,以便执行命令。我们可以使用绝对路径来执行命令,或者设置一个最小化的PATH: ```bash export PATH=/bin:/usr/bin:/sbin:/usr/sbin ``` 这样,基本的命令就可以使用了。 **步骤2:检查并修正`.bash_profile`** 使用文本编辑器(如`vi`)打开`~/.bash_profile`文件。注意,如果`vi`命令也找不到,可以使用绝对路径`/usr/bin/vi`。 ```bash /usr/bin/vi ~/.bash_profile ``` 在文件中查找对`PATH`的修改。通常,我们会看到类似这样的行: ```bash export PATH=$HOME/bin:$PATH ``` 或者 ```bash export PATH=/some/path:$PATH ``` 这种写法是将新路径添加到原有PATH的前面,一般是安全的。但有时可能会写成: ```bash export PATH=/some/path # 这样会覆盖原来的PATH,导致系统命令找不到 ``` 所以,确保在设置PATH时,保留原来的PATH(即包含`$PATH`)。例如: ```bash export PATH=$PATH:$HOME/bin:/path/to/mmlsquota ``` 另外,检查是否有其他命令在设置PATH之前执行,这些命令可能需要用到系统命令(如`tty`、`grep`),但此时PATH已被修改导致找不到命令。可以将这些命令移动到PATH设置之后执行。 **步骤3:处理`mmlsquota`命令报错** 如果`mmlsquota`命令报错,可能是因为该命令未安装或者其路径不在`PATH`中。 - 首先,使用`which`命令查找`mmlsquota`的位置(如果PATH已经部分恢复): ```bash which mmlsquota ``` 或者使用`find`命令: ```bash find / -name mmlsquota 2>/dev/null ``` - 如果找到,将其路径加入到`PATH`中。例如,如果`mmlsquota`在`/usr/lpp/mmfs/bin`下,则在`.bash_profile`中添加: ```bash export PATH=$PATH:/usr/lpp/mmfs/bin ``` - 如果没有找到,可能需要安装该命令所在的软件包(如GPFS相关软件包)。 **步骤4:重新加载配置文件** 修改保存后,重新加载配置文件: ```bash source ~/.bash_profile ``` 如果一切正常,命令应该可以正常使用。 为了防止配置文件错误导致无法登录,建议在修改前备份原文件。 **总结问题原因**: - 错误修改`PATH`环境变量,导致系统命令找不到。 - 在`PATH`被错误设置后,执行了依赖这些命令的脚本或命令,从而报错。 - `mmlsquota`命令可能未安装或路径未加入`PATH`。 §§相关问题§§ 1. 如何避免修改环境变量导致系统命令不可用? 2. Linux环境变量配置文件的加载顺序是怎样的? 3. 如何永久添加一个路径到PATH环境变量? </think> ### 解决~/.bash_profile加载时命令报错问题 #### 问题原因分析 1. **命令找不到(如 `tty`、`grep`)** 根本原因是 **`PATH` 环境变量被破坏或覆盖**,导致系统无法找到命令位置: - `/bin`、`/usr/bin` 等关键路径未包含在 `PATH` 中 - 配置文件(如 `~/.bash_profile`)中错误地重置了 `PATH` 变量 - 引用顺序错误导致路径丢失(参考引用[4]的配置文件加载顺序) 2. **`mmlsquota` 命令报错** 通常是: - 命令未安装(如 GPFS 工具包缺失) - 命令路径未加入 `PATH` - 环境变量配置冲突 --- #### 解决步骤(需用绝对路径执行命令) 1. **临时恢复 `PATH` 访问基本命令** 使用系统默认路径修复环境: ```bash /usr/bin/export PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/local/bin ``` 2. **检查配置文件中的 `PATH` 设置** 编辑 `~/.bash_profile`,确保 `PATH` 包含系统路径且 **增量添加**(参考引用[3][5]): ```bash /usr/bin/vi ~/.bash_profile ``` ```bash # 正确示例:保留原PATH内容 ($PATH) export PATH=$PATH:$HOME/bin # 在现有PATH后追加 # 错误示例:直接覆盖PATH会导致命令丢失 export PATH=$HOME/bin # 错误!覆盖系统路径 ``` 3. **验证 `mmlsquota` 命令状态** - 检查命令是否存在: ```bash /usr/bin/which mmlsquota # 查找命令位置 /usr/bin/find / -name mmlsquota 2>/dev/null ``` - 若不存在则需安装相关软件包(如 `gpfs.base`) - 若存在但不在 `PATH` 中,将其路径加入配置文件: ```bash echo 'export PATH=$PATH:/path/to/mmlsquota' >> ~/.bash_profile ``` 4. **修复环境变量加载顺序(关键)** 根据引用[4][5]的加载顺序规则: ```bash # 在 ~/.bash_profile 中显式加载 ~/.bashrc if [ -f ~/.bashrc ]; then . ~/.bashrc # 确保基础PATH优先加载 fi ``` 5. **重新加载配置** ```bash /usr/bin/source ~/.bash_profile # 使用绝对路径避免依赖失效PATH ``` --- #### 预防措施 1. **修改 `PATH` 时始终保留原值** ```bash export PATH=$PATH:/new/path # ✅ 正确 export PATH=/new/path # ❌ 危险! ``` 2. **复杂配置拆分到独立文件** ```bash # 在 ~/.bash_profile 中添加 if [ -d ~/.bashrc.d ]; then for f in ~/.bashrc.d/*; do . $f; done fi ``` 将自定义设置放入 `~/.bashrc.d/` 目录(如 `mmlsquota.sh`),避免污染主文件[^3]。 3. **使用 `command -v` 检查命令可用性** ```bash # 在脚本中添加保护逻辑 if ! command -v tty &>/dev/null; then export PATH="/bin:$PATH" # 紧急恢复路径 fi ``` > 通过修正 `PATH` 设置和加载顺序,可解决命令丢失问题;`mmlsquota` 报错需单独确认安装和路径配置[^1][^3][^4]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值