Linux/Unix: grep Command Show Line Numbers While Displaying Output
The grep command is used to search for a pattern in a file or files. To display the line numbers along with the matching lines, you can use the
- option.Here's an example:
grep -n 'pattern' file.txtIn this example,
patte is the string you're searching for, and file.txt is the file you're searching in. The - option causes grep to display the line number of each matching line.You can also use grep to search for a pattern in multiple files by specifying the file names separated by spaces:
grep -n 'pattern' file1.txt file2.txt file3.txtIf you want to search for a pattern recursively in a directory and its subdirectories, you can use the -r option:
grep -nr 'pattern' directoryIn this example, directory is the top-level directory you want to search in. The -r option causes grep to search recursively in all subdirectories of directory. The
- option causes grep to display the line number of each matching line.