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.
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.
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.
Use grep -n string file to find the line number without opening the file.
'#' 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.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With