How to Get a Line Number of a Pattern in UNIX

A pattern is any keyword or a phrase that occurs within files. A search of the file content is a common task that involves finding a required pattern. When you search a large file, you often need to know at which exact line a particular pattern occurs. Lines in any file are numbered consecutively beginning with one. Fortunately, you can use the "grep" command in the UNIX operating system to accomplish the required task.

Instructions

    1

    Right-click on the "Desktop" in UNIX, and then click on "Terminal" to open the command prompt window.

    2

    Type the command "cd directory_name" in the command prompt window to change to the directory where files of interest are located. For example, if the name of the directory was "Documents," you would type "cd documents."

    3

    Type the command "grep -n pattern filename," and then press "Enter." For example, if the pattern was "June" and the filename was "report.doc," you would type "grep -n June report.doc." That example finds all instances of the pattern "June" in the file "report.doc."

    4

    Read the program output. The line number is printed at the beginning of each line where the pattern is found. For example, in "21: June," 21 is the line number where the word "June" is found.

Blog Archive