How to Get the First Character from Bash String? [8 Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

In Bash scripting, extracting or getting the character is important for formatting and analyzing strings such as to validate, parse, and process texts.

To get the first character of a string in Bash, check the following methods:

  1. Using parameter expansion: ${parameter:start_index:length}
  2. Using the cut command: echo "$input_string" | cut -cN
  3. Using the sed command: sed  's/^\(.\).*/\1/'
  4. Using the grep command: grep -o 'action'
  5. Using the awk command: echo "input_str" | awk '{print substr($input_str,start_index, length)}'
  6. Using the printf command: printf "%.1s" "$input_string"
  7. Using the expr command: expr substr "$input_string" start_index length
  8. Using the perl command:  echo "$input_string" | perl [option] 'action'

Dive into the article to learn these methods of how to use Bash to get the first character from a string in detail.

1. Using Parameter Expansion

Parameter expansion allows you to retrieve and manipulate the value stored in the parameter or variable. With parameter expansion, you can easily get the first character of a string. The basic syntax for extracting a substring or character from an input string:

${parameter:offset:length}

Replace the parameter with the input string, offset with the position you want to extract the character, and length with how many characters you want to extract.

To get the first character from a bash string using parameter expansion, check the following script:

#!/bin/bash

# Define the string
input_string="This is the first string."

# Extract the first character
first_char="${input_string:0:1}"

# Print the first character
echo "The extracted first character: $first_char"
EXPLANATION

Firstly the script declares the input string in a variable named input_string. Then ${input_string:0:1} extracts the input string’s first character and stores it in a variable named first_char. At last, the echo command prints the output in the terminal.

Get the first character using parameter expansion

The output shows that the script has successfully gotten the first character “T” from the input string “This is the first string.”.

Note: To store the result in a file, use the following code:

echo "The extracted first character: $first_char" > "$output_file"

This command stores the character in the file name output_file. If the file does not exist then this command will create a new file otherwise it overwrites the existing content.

2. Using “cut” Command

In bash scripting, the cut command mainly extracts characters, bytes, and fields from the input string. Use the -c option with following a number which indicates the position of the character you want to extract. For example, if you want to get the Nth character from an input string, you can use -cN which will extract the specific character.

To get the first character from a string using the cut command, check out the script below:

#!/bin/bash

# Define the string
input_string="Another string."

# Get the first character using cut command
first_char=$(echo "$input_string" | cut -c1)

# Print the first character
echo "The first character of the input string: $first_char"
EXPLANATION

The cut command takes the output of the echo command through the pipe operator (|). The cut -c1 cuts the input string’s first character and stores it in a new variable named first_char.

Using cut command to get the first character

The script has gotten the first character “A” from the input string “Another string.”.

3. Using “sed” Command

The sed command is a simple yet very useful command to remove characters, replace strings, match patterns, and manipulate files and texts. The basic syntax to get the first character from a string is s/^\(.\).*/\1/. To get the first character from the input string using the sed command check out the following script:

#!/bin/bash

# Define the string
input_string="Hello, world!"

# Get the first character using sed
first_char=$(echo "$input_string" | sed 's/^\(.\).*/\1/')

# Print the first character
echo "The first character: $first_char"
EXPLANATION

At first, the script declares the input string in a variable named input_string. After that, the pipe operator (|) redirects the output of the echo command to the sed command. In the sed command, the^matched the starting of the input string. Then the\(.\)catches the first character of the string. After doing this, the sed command matches the rest of the characters using the.*. At last, the \1replaces all the remaining characters with the first character.

Getting the first character using sed command

The script has extracted the first character “H” from the input string ‘Hello, world!’.

4. Using “grep” Command

The grep command is an easy-to-search and match pattern of characters of a string and file. Using the grep command with the -o option will print the match character or line from the input string.

To get the first character from an input string using the grep command, use the following script:

#!/bin/bash

# Define the string
input_string="Hello, world!"

# Get the first character using grep
first_char=$(echo "$input_string" | grep -o '^.')

# Print the first character
echo "The first character: $first_char"
EXPLANATION

The pipe operator redirects the output of the echo command to thegrepcommand. Then, the grep -o '^.'matches the first character of the input string. Then theechocommand prints only the matched character. 

Bash get the first character of string using grep command

The output shows that the script has extracted the first character “H” from the input string ‘Hello, world!’.

5. Using “awk” Command

To get the first character from the input string, you can use the awk command with substr() function. Theawkis a versatile command tool used for text processing, handling multi-byte characters, and especially for pattern matching and manipulation. Check the following script below:

#!/bin/bash

# Define the string
input_string="# a special character in bash"

# Get the first character using awk
first_char=$(echo "$input_string" | awk '{print substr($0, 1, 1)}')

# Print the first character
echo "The first character: $first_char"
EXPLANATION

At first, the script declares the input string namedinput_string. The pipe operator takes the output of theechocommand to theawkcommand. In the awk command, the substr function extracts a substring. The$0refers to the entire input string. Then the first1indicates the starting position of the substring and the second1indicates the length of the substring which will extract the first character as both the parameters are set at 1.

Get the first character of string in bash using awk command

From the image, you can see the script has successfully extracted the first character “#” from the input string.

How to Get the First Character from Multiple Line Input?

When there are multiple newlines in an input string, then you can use the awk command to get the first character. Check out the following script:

#!/bin/bash

# Define the input string with multiple lines
input_string=$'The First line. \nIt is the Second line. \nHere is the Third line.'

# Use awk to extract the first character from each line
first_char=$(echo "$input_string" | awk '{print substr($0, 1, 1)}')

# Print the first characters
echo "First characters:"
echo "$first_char"

Get the first character of multiple line

The image shows that the script has got the first characters “T”, “I” and “H” from each line of the input strings.

Note: While declaring the string, use the single quote. Otherwise, it won’t show the expected result.

6. Using “printf” Command

The printf command in Linux is used to print and format the string, number, and special characters in the terminal. If you want to get the first character from a string using the printf command, then you have to use the format specifier that specifies the first character that will print in the terminal.

Navigate through the script below to get the first character from a string using the printf command:

#!/bin/bash

# Define the string
input_string="Hello, world!"

# Get the first character using printf
character=$(printf "%.1s" "$input_string")

# Print the first character
echo "The first character of the input string: $character"
EXPLANATION

In theprintfcommand,%.1sformat specifier prints the first character of the input string and the script stores the value to a variable namedcharacter. Thenechocommand prints the final output.

Bash get the first character of string using printf command

The output shows that the printf command prints only the first character “H” of the input string.

7. Using “expr” Command

Using thesubstrfunction, you can utilize the expr command to get the first character from the input string. The basic syntax for getting any character or substring is:

expr substr "$input_string" [position] [length]

To get the first character from the input string using theexprcommand, take a look at the following script:

#!/bin/bash

# Define the string
input_string="Last input string."

# Get the first character using expr
first_char=$(expr substr "$input_string" 1 1)

# Print the first character
echo "The first character: $first_char"
EXPLANATION

Thesubstrfunction extracts the character at position1taking the length of1character and the script stores the output to a variable namedfirst_char. At last, the echo command prints the value of the string.

Using the expr command get the first character of string in bash

The script has extracted the first character “L” from the input string.

8. Using “perl” Command

In bash scripting, the perl command gets the first character from the input string by using the regular expression and slicing. In the slicing process, the script defines the starting position and length of the desired substring.

To get the first character from the input string usingperlcommand, check the following script:

#!/bin/bash

# Define the input string
input_string="Hello, world!"

# Use Perl to extract the first character
first_char=$(perl -e "print substr('$input_string', 0, 1)")

# Print the result
echo "The first character: $first_char"
EXPLANATION

In the $(perl -e "print substr('$input_string', 0, 1)"), the -e option executes the perl code inline. Then it uses the substr function to extract the character. Here, the0indicates the starting position of the character and1indicates the length of the character to be extracted.

bash get the first character of string using the perl command

The image shows that the perl command has extracted the first character “H” from the input string.

How to Get the First Character of Each Element of an Array?

To get the first character of each element of an array, you can use parameter expansion inside a loop where the loop iterates over each element and extracts the first character from each element string of the input array.

The following script below shows how to do it:

#!/bin/bash

# Define an array
input_array=("apple" "banana" "cherry" "date")

# Loop through the array and extract the first character of each element
for element in "${input_array[@]}"; do
   first_char="${element:0:1}"
   echo "$first_char"
done
EXPLANATION

Firstly the script declares an array with four elements in a variable namedinput_array. Then, it uses a for loop that iterates over each element of the input array. The${input_array[@]}expands each element for the for loop. Inside the loop, the script uses the parameter expansion ${element:0:1}that extracts a character starting from the index position0, and the length of the substring is defined using1. After that, th echocommand prints each of the values.

Extracting the first character of each element of an array

The image shows that the script has got the first characters a,b,c, and d from the elements “apple”, “banana”, “cherry” and “date” of the input array respectively.

How to Get the First Character of Each Substring?

Generally, a large string contains multiple substrings. To get each first character from the input string, first split the string into substrings using space (" ") as the delimiter and then loop over the substrings to get the first character. Take a look at the following script for example:

#!/bin/bash

# Define the input string
string="This is a string."

# Define the delimiter
delimiter=" "

# Use the delimiter to split the input string into substrings
IFS="$delimiter" read -ra substrings <<< "$string"

# Iterate over each substring and extract the first character
for substring in "${substrings[@]}"; do
   first_char="${substring:0:1}"
   echo "$first_char"
done
EXPLANATION

Firstly the script splits the input string into multiple substrings based on the delimiter which is set as space. Then with read -ra substrings <<< "$string", thereadcommand reads the substrings, and the-raoption tells the read command to store the substrings into an array named substrings. After that, the for loop iterates over each element of the array. By using ${substring:0:1}, the loop extracts each of the first characters. At last, theechocommand inside the loop, prints the first character of the input string.

Extracting multichar from multiple lines of an input string

The output shows that the script has extracted each of the characters from the substrings of the input string.

Conclusion

In conclusion, this article illustrates several methods to get the first characters from an input string. It also demonstrates how you can get the first character from multiple lines, from each element of the array. Among these methods, using the sed, perl, and awk commands offers more flexibility and versatility than others.

People Also Ask

Can I get the first character from an input string?

Yes, you can get the first character simply using the parameter expansion. In the parameter expansion use the variable that contains the input string. To extract the character you need to specify the parameter for the substring. For example to extract the first character you have to use the ${input_string:0:1}.

How do I get the first word from a string?

To get the first word, you can use any method such as parameter expansion, awk, cut, perl command. For example, if you want to extract the first word from a string “Hello World!”, then use $(echo "$string" | awk '{print $1}'). In this code, the awk command takes the output of the echo command through the pipe operator. In the awk command, the {print $1} prints the first word of the input string.

How to get the second character from a string?

To get the second character from a string, you can use parameter expansion and other external commands such as cut, awk, sed, and perl. For example, the command $(echo "$string" | cut -c2) extracts the second character from the variable $string.

What is the first position of a string in Bash?

The first position of a string starts with index 0. Some programming languages use the first index as 1. In Bash, the first index is represented with 0. For example, you want to show the first character of a string, then use the string variable with 0 indexing like first_char="${string:0:1}"

How to check if the first character of a string is a slash?

To check whether the first character of a string is a slash or not, then you can use the conditional expression if [ "${string:0:1}" = "/" ]. The expression compares whether the first character is slash or not.

Check out the following script:

#!/bin/bash

string="/ hello"

if [ "${string:0:1}" = "/" ]; then
   echo "The first character is a slash."
else
   echo "The first character is not a slash."
fi

#Output: The first character is a slash.

If the condition is true (first character is /) then it prints “The first character is a slash”.

Related Articles


<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial

4.7/5 - (4 votes)
Afia Zahin Oishi

Assalamualaikum, I am Afia Zahin, completed my graduation in Biomedical Engineering from Bangladesh University of Engineering and Technology, currently working as a Linux Content Developer Executive at SOFTEKO. A high achieving professional with a strong work ethic and able to work in a team in order to consistently achieve my goal and build my skillset. Able to handle difficult problems with patience and swift decision-making. Read Full Bio

Leave a Comment