如何使用 while 循环逐行读取文件中的行,并在每次迭代中,grep 每一行以与字符串进行比较?

age*_*on7 2 command-line grep

我有一个名为 abc.txt 的文件,其内容如下:

1: It is a shell script
2: There are few lines in this file
3: I am good with programming in C, but beginner in shell
4: We are going towards end of file
5: END OF FILE
Run Code Online (Sandbox Code Playgroud)

我想迭代地读取每个文件,并且在每次迭代中,我想将这行与“我擅长 C 编程,但初学者在 shell 中”进行比较,然后进行一些处理。

任何帮助将不胜感激。谢谢!

Ser*_*nyy 9

使用 shell 循环是不必要的,因为grep已经迭代了几行:

grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt
Run Code Online (Sandbox Code Playgroud)

如果有匹配的行,它将被打印出来。[0-9]定义将匹配的字符范围。我们还可以将其扩展到更长的数字[0-9]*:(我认为使用 perl regex-P选项可以作为[0-9]+:)。

如果真的需要shell循环,我们可以使用case语句进行模式匹配

grep '^[0-9]:  I am good with programming in C, but beginner in shell' input.txt
Run Code Online (Sandbox Code Playgroud)


Geo*_*sen 8

尝试使用此示例代码来帮助识别和修改以满足您的需求:

#!/usr/bin/env bash
set -e
set -x 

while read -r linenum line
do
        if [ "$line" = "I am good with programming in C, but beginner in shell" ]
        then
                # Process things here
                echo "same"
        fi
done < "$1"
Run Code Online (Sandbox Code Playgroud)

用法:

信息:

  • -r: 传递给 read 命令的选项可防止反斜杠转义被解释。
  • set -e: Bash 选项用于在第一次错误时停止脚本。
  • set -x:用于调试脚本的 Bash 选项。
  • "$1":在这种情况下传递给脚本的文件变量 data.txt
  • linenum: bash 将读取的行拆分为两个变量而另一个通过lin变量传入时保存行号的变量。

  • @George 所以你使用 `-d" "` 来分割空白并从第二行开始剪切所有行。我建议另一种方式:`while IFS= read -r linenum line`。shell 将在输入行上执行分词并将第一项(行号)放入 `linenum` 变量中,但所有其他内容都将放入 `line` 变量中。除了其他事情之外,`case` 语句可以用作 `[[` 比较的替代。 (2认同)