Languages
[Edit]
EN

Bash - cut n first characters from string

10 points
Created by:
Lani-Skinner
408

in this article, we would like to show how to remove first N characters from some string in Bash.

Quick solution (cutting 2 first characters):

#                        2+1
#                        |
#                        v
echo "123456" | tail -c +3   # 3456

Where: tail -c +3 cuts first characters starting counting them from 1.

Output:

3456

 

Practical example

In this section, you will find a reusable function that cuts text.

#!/bin/bash

function cut_text()  # text, offset
{
    echo "$1" | tail -c "+$(($2 + 1))"
}


# Usage example:

offset=2
text="123456"

result="$(cut_text "$text" "$offset")"

echo "$result"   # 3456

See also

  1. Bash - get n first characters from string 
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join