EN
Bash - cut n first characters from string
10 points
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):
xxxxxxxxxx
1
# 2+1
2
# |
3
# v
4
echo "123456" | tail -c +3 # 3456
Where:
tail -c +3
cuts first characters starting counting them from 1.
Output:
xxxxxxxxxx
1
3456
In this section, you will find a reusable function that cuts text.
xxxxxxxxxx
1
2
3
function cut_text() # text, offset
4
{
5
echo "$1" | tail -c "+$(($2 + 1))"
6
}
7
8
9
# Usage example:
10
11
offset=2
12
text="123456"
13
14
result="$(cut_text "$text" "$offset")"
15
16
echo "$result" # 3456