FUNDAMENTALS A Complete Guide for Beginners
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:
- Using parameter expansion:
${parameter:start_index:length}
- Using the cut command:
echo "$input_string" | cut -cN
- Using the sed command:
sed 's/^\(.\).*/\1/'
- Using the grep command:
grep -o 'action'
- Using the awk command:
echo "input_str" | awk '{print substr($input_str,start_index, length)}'
- Using the printf command:
printf "%.1s" "$input_string"
- Using the expr command:
expr substr "$input_string" start_index length
- 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}
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"
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.
The output shows that the script has successfully gotten the first character “T” from the input string “This is the first string.”.
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"
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
.
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"
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 \1
replaces all the remaining characters with the first character.
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"
The pipe operator redirects the output of the echo command to thegrep
command. Then, the grep -o '^.'
matches the first character of the input string. Then theecho
command prints only the matched character.
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. Theawk
is 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"
At first, the script declares the input string namedinput_string
. The pipe operator takes the output of theecho
command to theawk
command. In the awk command, the substr function extracts a substring. The$0
refers to the entire input string. Then the first1
indicates the starting position of the substring and the second1
indicates the length of the substring which will extract the first character as both the parameters are set at 1
.
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"
The image shows that the script has got the first characters “T”, “I” and “H” from each line of the input strings.
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"
In theprintf
command,%.1s
format specifier prints the first character of the input string and the script stores the value to a variable namedcharacter
. Thenecho
command prints the final output.
The output shows that the printf command prints only the first character “H” of the input string.
7. Using “expr” Command
Using thesubstr
function, 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 theexpr
command, 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"
Thesubstr
function extracts the character at position1
taking the length of1
character and the script stores the output to a variable namedfirst_char
. At last, the echo command prints the value of the string.
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 usingperl
command, 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"
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, the0
indicates the starting position of the character and1
indicates the length of the character to be extracted.
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
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 echo
command prints each of the values.
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
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"
, theread
command reads the substrings, and the-ra
option 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, theecho
command inside the loop, prints the first character of the 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 per
l. 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
- How to Convert a Bash String to Int? [8 Methods]
- How to Format a String in Bash? [Methods, Examples]
- How to Convert Bash String to Uppercase? [7 Methods]
- How to Convert Bash String to Lowercase? [7 Methods]
- How to Replace String in Bash? [5 Methods]
- How to Trim String in Bash? [6 Methods]
- How to Truncate String in Bash? [5 Methods]
- How to Remove Character from String in Bash? [7+ Methods]
- How to Remove First Character From Bash String? [7 Methods]
- How to Remove Last Character from Bash String [6 Methods]
- How to Use String Functions in Bash? [Examples Included]
- How to Generate a Random String in Bash? [8 Methods]
- How to Manipulate Bash String Array [5 Ways]
- How to Use “Here String” in Bash? [Basic to Advance]
- Encode and Decode with “base64” in Bash [6 Examples]
- How to Use “eval” Command in Bash? [8 Practical Examples]
<< Go Back to String Manipulation in Bash | Bash String | Bash Scripting Tutorial