Removing First and Last Characters From Strings in Bash

From the following article, you’ll learn how to remove first characters from the beginning of each line in Bash and how to print strings between first and last characters using cut command.

You’ll also learn how to remove last characters of each line using trick with reverse command.

I’ve created a file with the following content and I’ll use it in examples below. So lets say we need to remove first and last characters of each line from the given file.

$ cat file
12345===I Love Bash===54321
12345===I Love Bash===54321
12345===I Love Bash===54321

Remove First N Characters Of Each Line

Use the following command to delete first 5 characters of each line (trim first 5 characters and print each line starting from the 6th character):

$ cat file | cut -c 6-
===I Love Bash===54321
===I Love Bash===54321
===I Love Bash===54321

Print Strings Between First and Last Characters

Use the following command to print strings between 9th and 20th characters of each line in Bash:

$ cat file | cut -c 9-20
I Love Bash
I Love Bash
I Love Bash

Print First N Characters Of Each Line

Use the following command to print first 20 characters of each line in Bash:

$ cat file | cut -c 1-20
12345===I Love Bash
12345===I Love Bash
12345===I Love Bash

Remove Last Character Of Each Line

Using combination of reverse and cut commands we can remove last N characters of each line, as shown below. (source)

Use the following command to delete last character of each line in Bash:

$ rev file | cut -c 2- | rev
12345===I Love Bash===5432
12345===I Love Bash===5432
12345===I Love Bash===5432

Remove Last N Characters Of Each Line

Use the following command to delete last 8 characters of each line in Bash:

$ rev file | cut -c 9- | rev
12345===I Love Bash
12345===I Love Bash
12345===I Love Bash

One Reply to “Removing First and Last Characters From Strings in Bash”

  1. ПервыйНах!
    Статья весьма полезная, т.к. man cut не страдает избытком Информативности и Примеров.
    Но почему в Заголовке написано про Bash, если Статья про cut?
    Подобные Вещи должны работать в Любой ∗nix Системе из под Любого Shell.

Leave a Reply