Here is a simple example on how to search a file and instead of printing a matching string to STOUT we only print a line number for a matching string. For an example consider a following file:
$ nl test.txt 1 linux 2 bash 3 shell 4 power 5 linux 6 shell 7 command 8 GNU
First use the -n
option to print line numbers for a matching string shell
:
$ grep -n shell test.txt 3:shell 6:shell
As a last step pipe the STDOUT to a cut
command:
$ grep -n shell test.txt | cut -d : -f1 3 6
If you need the output on a single line add one more pipe to tr
command to remove all new line characters and replace them with single space:
grep -n shell test.txt | cut -d : -f1 | tr "\n" " " 3 6