Remove the First and Last Character of a Line with sed (Linux)

Category: Linux How-To
Posted: October 8, 2019
Author: Antonio

Continuing the series on useful console commands, this time it’s sed.

sed & awk book

In one of my scripts I needed to remove the first and the last character of each line. You can do it with sed.


A working example:

cat 1.txt | sed -e "s/^.//;s/.$//"

The command prints a text file and uses a sed regular expression to replace the first and the last character of every line with nothing, which simply deletes them.

The number of dots controls how many characters are removed (a dot matches any single character, so one dot is one character). For example, to remove the first two and the last two characters:

sed -e "s/^..//;s/..$//" 1.txt
Related posts:

Leave a Comment

Copying content from this site is allowed only with a direct link to the source - https://nemcd.com