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.
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 to get the line number of a match. Ok, so grep -n would return the line that contains the words AND the line number.
Open a Notepad file.Go to View and select Status Bar. Enter text and move the cursor to the line you want to find the number for. Look at the bottom in the status bar and you will see the line number.
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.
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
.
Use command substitution:
n=$(awk '/word/{print NR}' file)
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)
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