EN
Bash - get n first characters from string
7 points
in this article, we would like to show how to get first N characters from some string in Bash.
Quick solution:
xxxxxxxxxx
1
echo "123456" | head -c +3
Where:
+3
indicates amount of the characters to get.
Output:
xxxxxxxxxx
1
123
In this section, you will find a reusable function that gets a text.
xxxxxxxxxx
1
2
3
function get_text() # args: text, count
4
{
5
echo "$1" | head -c "+$2"
6
}
7
8
9
# Usage example:
10
11
count=3
12
text="123456"
13
14
result="$(get_text "$text" "$count")"
15
16
echo "$result" # 123