bash 使用grep获取文件中字符串第一次出现的行号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22019847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:41:48  来源:igfitidea点击:

Using grep to get the line number of first occurrence of a string in a file

bashawkgrep

提问by user1651888

I am using bash script for testing purpose.During my testing I have to find the line number of first occurrence of a string in a file. I have tried "awk" and "grep" both, but non of them return the value.

我使用 bash 脚本进行测试。在测试期间,我必须找到文件中字符串第一次出现的行号。我已经尝试过“awk”和“grep”,但它们都没有返回值。

Awk example

awk 例子

#/!bin/bash
....
VAR=searchstring
...
cpLines=$(awk '/$VAR/{print NR}' $MYDIR/Configuration.xml

this does not expand $VAR. If I use the value of VAR it works, but I want to use VAR

这不会扩展 $VAR。如果我使用 VAR 的值它可以工作,但我想使用 VAR

Grep example

示例

#/!bin/bash
...
VAR=searchstring    
...
cpLines=grep -n -m 1 $VAR $MYDIR/Configuration.xml |cut -f1 -d: 

this gives error line 20: -n: command not found

这给出了错误行 20: -n: command not found

回答by enterx

grep -n -m 1 SEARCH_TERM FILE_PATH |sed  's/\([0-9]*\).*//'

grep switches

grep 开关

-n = include line number

-n = 包括行号

-m 1 = match one

-m 1 = 匹配一个

sed options (stream editor):

sed 选项(流编辑器):

's/X/Y/'- replace X with Y

's/X/Y/'- 用 Y 替换 X

\([0-9]*\)- regular expression to match digits zero or multiple times occurred, escaped parentheses, the string matched with regex in parentheses will be the \1 argument in the Y (replacement string)

\([0-9]*\)- 匹配数字零次或多次出现的正则表达式,转义括号,括号中与正则表达式匹配的字符串将是Y中的\1参数(替换字符串)

\([0-9]*\).*- .*will match any character occurring zero or multiple times.

\([0-9]*\).*-.*将匹配出现零次或多次的任何字符。

回答by Raul Andres

You need $() for variable substitution in grep

你需要 $() 在 grep 中进行变量替换

cpLines=$(grep -n -m 1 $VAR $MYDIR/Configuration.xml |cut -f1 -d: )

回答by jaypal singh

Try something like:

尝试类似:

awk -v search="$var" '
grep -n -m 1 SEARCH_TERM FILE_PATH | grep -Po '^[0-9]+'
~search{print NR; exit}' inputFile

In awk, / /will interpret awkvariable literally. You need to use match(~) operator. What we are doing here is looking for the variable against your input line. If it matches, we print the line number stored in NRand exit.

awk,/ /将按awk字面解释变量。您需要使用match( ~) 运算符。我们在这里所做的是根据您的输入行查找变量。如果匹配,我们打印存储在其中的行号NR并退出。

-vallows you to create an awkvariable (search) in above example. You then assign it your bashvariable ($var).

-v允许您在上面的示例中创建awk变量 ( search)。然后您将其分配给您的bash变量 ( $var)。

回答by jiangdongzi

 -Po = -P -o

explanation:

解释:

##代码##

-Puse perl regex

-P使用 perl 正则表达式

-oonly print matched string (not the whole line)

-o只打印匹配的字符串(不是整行)

回答by Joshua Trimm

Try pipping;

尝试吸管;

grep -P 'SEARCH TERM' fileName.txt | wc -l

grep -P 'SEARCH TERM' fileName.txt | wc -l