Languages
[Edit]
EN

Bash - get n first characters from string

7 points
Created by:
Khloe-Kaiser
398

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

See also

  1. Bash - cut 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