Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Bash Script to Find Line Number of String in File

How can I use a bash script to find the line number where a string occurs?

For example if a file looked like this,

Hello I am Isaiah This is a line of text. This is another line of text. 

and I ran the script to look for the string "line" it would output the number 2, as it is the first occurance.

like image 596
David L. Rodgers Avatar asked Nov 17 '13 02:11

David L. Rodgers


People also ask

How do I count the number of lines in a file in bash?

wc. The wc command is used to find the number of lines, characters, words, and bytes of a file. To find the number of lines using wc, we add the -l option. This will give us the total number of lines and the name of the file.

How do you show the line number in a string in Linux?

The -n ( or --line-number ) option tells grep to show the line number of the lines containing a string that matches a pattern. When this option is used, grep prints the matches to standard output prefixed with the line number.

How do I search for line numbers in a file?

Use grep -n string file to find the line number without opening the file.

How do I count strings in bash?

'#' symbol can be used to count the length of the string without using any command. `expr` command can be used by two ways to count the length of a string. Without `expr`, `wc` and `awk` command can also be used to count the length of a string.


2 Answers

Given that your example only prints the line number of the first occurrence of the string, perhaps you are looking for:

awk '/line/{ print NR; exit }' input-file 

If you actually want all occurrences (eg, if the desired output of your example is actually "2\n3\n"), omit the exit.

like image 131
William Pursell Avatar answered Sep 21 '22 23:09

William Pursell


I like Siddhartha's comment on the OP. Why he didn't post it as an answer escapes me.

I usually just want the line number of the first line that shows what I'm looking for.

lineNum="$(grep -n "needle" haystack.txt | head -n 1 | cut -d: -f1)" 

Explained: after the grep, grab just the first line (num:line), cut by the colon delimiter and grab the first field

like image 45
hanzo2001 Avatar answered Sep 22 '22 23:09

hanzo2001