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:
echo "123456" | head -c +3
Where:
+3
indicates amount of the characters to get.
Output:
123
Practical example
In this section, you will find a reusable function that gets a text.
#!/bin/bash
function get_text() # args: text, count
{
echo "$1" | head -c "+$2"
}
# Usage example:
count=3
text="123456"
result="$(get_text "$text" "$count")"
echo "$result" # 123