1. query the row number of the string.
Grep-n "XXX" str.txt #-N print the prefix of the number of lines where the character "XXX" is located in the file "stringstr.txt"
Example:
Str.txt
Xxx
Yyy
Zzz
Xxx
Enter the SEARCH Command: grep-n "XXX" str.txt
The result is as follows:
1: XXX
4: XXX
The row number is 1, 4, and matches the string "XXX". The two are separated by colons ":".
2. Find the row number that the string matches for the first time.
Grep-n "XXX" str.txt | head-1
The result is as follows:
1: XXX
Similarly, search for the last matched row number.
Grep-n "XXX" str.txt | tail-1
The result is as follows:
4: XXX
Find the row number that the second string matches
Grep-n "XXX" str.txt | head-2 | tail-1 # extract the first two rows and then the last row
The result is as follows:
4: XXX
3. Extract the row number of the string.
Grep-n "XXX" str.txt | cut-d ":"-F 1
First query all the line numbers of the string "XXX", and then use the cut command to separate the ":" character to extract the first field, that is, the line number.
The result is as follows:
1
4
Extract the row number of the first match
Grep-n "XXX" str.txt | head-1 | cut-d ":"-F 1
The result is as follows:
1
4. Compare the variation of two string row numbers
Two files: str.txt and str2.txt
Str.txt
Xxx
Yyy
Zzz
Xxx
Str2.txt
Yyy
Xxx
WWW
Zzz
Compare row number scripts
Catline. Sh
#!/bin/bashrm -rf ret.txttotal=`wc -l $1 | awk '{print $1}'`echo "total = $total"num=1while read linedo echo $line ret=`grep -n $line $2 | head -1` echo $ret if [ -z $ret ]; then num2=$total echo "null num2 = $total" else num2=`echo $ret | cut -d ":" -f 1` echo "num2 = $num2" fi echo $num change=`expr $num2 - $num` echo "$num2 - $num = $change" num=`expr $num + 1` echo "$line=$change" >> ret.txtdone < $1cat ret.txt
Run the script command:
./Catline. Sh str2.txt str.txt
The running result is as follows:
total = 4yyy2:yyynum2 = 212 - 1 = 1xxx1:xxxnum2 = 121 - 2 = -1wwwnull num2 = 434 - 3 = 1zzz3:zzznum2 = 343 - 4 = -1yyy=1xxx=-1www=1zzz=-1