How to Use sed to Print First n Characters of Line


Often you may want to use sed to print the first n characters of each line in a file.

You can use the following basic syntax to do so:

sed -n '{s/^\(.\{4\}\).*/\1/g;p}' cities.txt

This particular example will print the first 4 characters of each line in the file named cities.txt.

To print a different number of characters from the start of each line, simply replace the 4 with a different number.

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

Example: Use sed to Print First n Characters of Each Line

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 print the first 4 characters of each line in the file.

We can use the following syntax to do so:

sed -n '{s/^\(.\{4\}\).*/\1/g;p}' cities.txt

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

sed print first n characters of line

Notice that this prints the first 4 characters from each line of the file.

To print a different number of characters, simply change the 4 to a different number.

For example, we can use the following syntax to instead print the first 5 characters from each line:

sed -n '{s/^\(.\{5\}\).*/\1/g;p}' cities.txt

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

Notice that this prints the first 5 characters from each line of the file, just as we specified.

Related Tutorials

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

How to Use sed to Print Out Line Numbers
How to Use sed to Print Specific Lines in File
How to Use sed to Print Every nth Line of File
How to Use sed to Print All Lines Between Two Patterns

Leave a Reply