How to Use grep to Find Lines that Exceed Certain Length


Often you may want to use the grep command in Bash to find all lines in a file that exceed a certain length.

You can use the following basic syntax to do so:

grep '.\{8\}' cities.txt

This particular example will return only the lines from the file named cities.txt that are 8 characters or longer.

Note that spaces are included in the character count.

The following example shows how to use this syntax in practice.

Example: How to Use grep to Find Lines that Exceed Certain Length

Suppose that we have a file named cities.txt that contains the names of various U.S. cities.

We can use the cat command to view the contents of this file:

Suppose that we would like to return each line in the file that is 8 characters or longer.

We can use the following syntax to do so:

grep '.\{8\}' cities.txt

The following screenshot shows how to use this syntax in practice:

grep lines greater than length

Notice that this returns the following lines from the file:

  • Sacramento
  • Cincinnati
  • Milwaukee

Each of these city names are 8 characters or longer.

Feel free to change the 8 to any number that you would like to instead find lines that exceed a different length.

Bonus: If you’d like to find the length of the longest line in the file, you can use the following syntax:

wc -L cities.txt

The following screenshot shows how to use this syntax in practice:

This tells us that the longest line in the file is 10 characters long.

This can be helpful to know if any line in a file exceeds a specific length you have in mind.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Use grep to Get Line Number of Match
How to Use grep to Extract Last Occurrence in File
How to Use grep to List All Files Containing Specific String

Leave a Reply