Bash: Filter for Lines in File that Start with Specific String


Often you may want to use Bash to filter for lines in a file that start with a specific string.

You can use the following methods to do so:

Method 1: Filter for Lines that Start with Specific String

grep -E '^(Ma)' data1.csv

This particular example will filter the CSV file named data1.csv to only display the rows that start with the string Ma.

Note that the -E operator specifies that you’re using an extended regular expression and the ^ character represents the start of a line in Regex.

Method 2: Filter for Lines that Start with One of Several Specific Strings

grep -E '^(Ma|La)' data1.csv

This particular example will filter the CSV file named data1.csv to only display the rows that start with either the string Ma or La.

Note that the | operator is used to represent “or” logic in Regex.

The following examples show how to use each method in practice.

Example 1: Filter for Lines that Start with Specific String

Suppose that we have a CSV file named data1.csv that contains information about various basketball players.

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

Suppose that we would like to filter the file to only display the rows that start with the string Ma.

We can use the following syntax to do so:

grep -E '^(Ma)' data1.csv

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

Bash filter lines starting with

Notice that this returns only the lines starting with the string Ma

Example 2: Filter for Lines that Start with One of Several Specific Strings

Suppose that we would like to filter the data1.csv file to only display the rows that start with the string Ma or La.

We can use the following syntax to do so:

grep -E '^(Ma|La)' data1.csv

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

Bash filter for lines in file that start with one of several strings

Notice that this returns only the lines starting with the string Ma or La.

Note: We used one | operator to specify two different starting strings to filter for but you can use several | operators to filter for even more strings.

Related Tutorials

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

Bash: How to Filter CSV File Based on Column Value
Bash: How to Extract Specific Columns from CSV File
Bash: How to Remove Last Character from String

Leave a Reply