How to print the line number where a string appear

2020-06-10 02:23发布

I have a specific word, and I would like to find out what line number in my file that word appears on.

This is happening in a c shell script.

I've been trying to play around with awk to find the line number, but so far I haven't been able to. I want to assign that line number to a variable as well.

标签: shell awk
4条回答
欢心
2楼-- · 2020-06-10 02:46

Using grep

To look for word in file and print the line number, use the -n option to grep:

grep -n 'word' file

This prints both the line number and the line on which it matches.

Using awk

This will print the number of line on which the word word appears in the file:

awk '/word/{print NR}' file

This will print both the line number and the line on which word appears:

awk '/word/{print NR, $0}' file

You can replace word with any regular expression that you like.

How it works:

  • /word/

    This selects lines containing word.

  • {print NR}

    For the selected lines, this prints the line number (NR means Number of the Record). You can change this to print any information that you are interested in. Thus, {print NR, $0} would print the line number followed by the line itself, $0.

Assigning the line number to a variable

Use command substitution:

n=$(awk '/word/{print NR}' file)

Using shell variables as the pattern

Suppose that the regex that we are looking for is in the shell variable url:

awk -v x="$url" '$0~x {print NR}' file

And:

n=$(awk -v x="$url" '$0~x {print NR}' file)
查看更多
Ridiculous、
3楼-- · 2020-06-10 02:57

Use the NR Variable

Given a file containing:

foo
bar
baz

use the built-in NR variable to find the line number. For example:

$ awk '/bar/ { print NR }' /tmp/foo
2
查看更多
干净又极端
4楼-- · 2020-06-10 02:58

Sed

You can use the sed command

 sed -n '/pattern/=' file

Explanation

The -n suppresses normal output so it doesn't print the actual lines. It first matches the /pattern/, and then the = operator means print the line number. Note that this will print all lines that contains the pattern.

查看更多
倾城 Initia
5楼-- · 2020-06-10 03:01

find the line number for which the first column match RRBS

awk 'i++ {if($1~/RRBS/) print i}' ../../bak/bak.db
查看更多
登录 后发表回答