Table of Contents
Using read
Command
Use the read
command with parameter expansion to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash myString="Hello:World:How:are:you?" read lastElement <<< "${myString##*:}" echo "The last element is: $lastElement" |
1 2 3 |
The last element is: you? |
In the above example, the read
command is used with the ${myString##*:}
parameter expansion to get the last element of the string which is then assigned to the lastElement
variable using the <<<
operator. Here, the ##
operator removes everything up to the string"s last colon(:
). In Bash, the ##
operator performs a greedy
match, meaning it removes the longest possible match of the pattern from the beginning of the string.
1 2 3 4 5 6 7 8 |
${ myString <-- from variable myString ## <-- greedy front trim * <-- matches anything : <-- until the last ':' } |
For example, in the above variable myString="Hello:World:How:are:you?"
, the *:
pattern matched everything up to the last colon, and the ##
operator is used to remove all of it, leaving only the last element of the string you?
. You can replace the colon(:
) with any character that we want to match.
Let"s see another example where you want to get the last element from the path.
1 2 3 4 5 6 |
#!/bin/bash path="/path/to/my/file.txt" read filename <<< "${path##*/}" echo "The last element of the Path is: $filename" |
1 2 3 |
The last element of the Path is: file.txt |
Here, the ${path##*/}
parameter expansion is used to get the last element of the path "/path/to/my/file.txt"
. The */
pattern matches everything up to and includes the last forward slash in the path, and the ##
operator removed all of it, leaving only the file name.
Do this if you want to get the last element of your current working directory.
1 2 3 4 5 6 7 |
#!/bin/bash dir=$(pwd); echo "Current Working Directory is: $dir" read filename <<< "${dir##*/}" echo "Last element is: $filename" |
1 2 3 4 |
Current Working Directory is: /home/cg/root/642c71d615527 Last element is: 642c71d615527 |
Using tr
Command
Use the tr
command to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash myString="This:is:a:String" lastElement=$(echo "$myString" | tr ':' '\n' | tail -n 1) echo "The last element is: $lastElement" |
1 2 3 |
The last element is: String |
The tr
command in Bash is typically used for transforming and deleting characters in a string or a file. Various types of transformation can be done by using this command, such as searching and replacing text.
In the above example, the input string "This:is:a:String"
is first piped to the tr
command, which replaces all occurrences of a delimiter character(:
) with newline characters(\n
), effectively splitting the string into multiple lines. Then, the output of tr
is passed to the tail
command. The tail
command is a utility in Linux and Unix operating systems used to print the last few lines of a string or a file.
Here, the -n
option, followed by the number 1
, is used to print only the last line. This allows us to extract the last element of a string split by tr
.
Using Cut
Command
Use the cut
command to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash string="Apple,Banana,Orange" lastElement=$(echo "$string" | rev | cut -d ',' -f 1 | rev) echo "The last element is: $lastElement" |
1 2 3 |
The last element is: Orange |
In this example, the "Apple,Banana,Orange"
string contained text with commas as separators. To extract the last element of this string, the rev
command is used to reverse the string. Then, the cut
command splits the reversed string at the first comma (,
) and selects the first field (-f 1
).
Finally, the rev
command is used again to reverse the resulting string to obtain the last element.
Using awk
Command
Use the awk
command to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash myString="some:text:with:colons" lastElement=$(echo $myString | awk -F ':' '{print $NF}') echo "The last element is: $lastElement" |
1 2 3 |
The last element is: colons |
In the above code snippet, the awk command is used to extract the last element of this string "some:text:with:colons"
with the -F
option to specify the colon (:
) as the field separator.
The NF
variable is automatically set by awk
and contains the number of fields in the current record. Here, It is used to reference the last field in a record, which is the last element of the string we want to extract.
Using grep
Command
Use the grep
command to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash myString="some text with spaces" lastElement=$(echo $myString | grep -oE '[^ ]+$') echo "The last element is: $lastElement" |
1 2 3 |
The last element is: spaces |
In this example, the string "some text with spaces"
contained text separated by spaces. The grep
command is used with the -oE
parameters to get the last element of this string.
- The
-o
parameter tells thegrep
command to output only the matching text. - The
-E
parameter enables regular expressions.
The regular expression [^ ]+$
is used to find one or more characters that are not spaces ([^ ]
) at the end of the line ($
).
Using sed
Command
Use the sed
command to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash myString="this is a sample string" lastElement=$(echo "$myString" | sed 's/.* //') echo "The last element is: $lastElement" |
1 2 3 |
The last element is: string |
In this example, the sed
command is used with the s
(substitute) command to match everything before the last space character in the input string and replace it with nothing.
In Bash, the sed
command performs text transformations on the input text. The "s"
character is used as the substitute command in sed
, which is used to search and replace a given pattern in the input text. In addition, the regular expression .*
is used to search any sequence of characters (except for newline) zero or more times; in other words, it matches everything before the last space character in the input text.
The last element in the string is effectively extracted by replacing everything before the last space character with nothing.
Using basename
Command
Use the basename
command to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash path="/path/to/my/file.txt" lastElement=$(basename "$path") echo "The last element is: $lastElement" |
1 2 3 |
The last element is: file.txt |
In the above example, the path
variable is set to the file path "/home/user/Documents/file.txt"
. Then, this variable is passed to the basename
command using the $()
syntax to execute the command and capture its output. In Bash, the basename
command is used to get the last element of the file path. That, in this case, is the file name file.txt
.
Note that the basename
command removes any leading directory components from the input path and returns only the final file or directory name. If the input path ends with a trailing slash, the basename
command returns an empty string as output.
Using IFS
Command
Use the IFS
(Internal Field Separator) variable with a delimiter to split the string and get the last element in Bash.
1 2 3 4 5 6 |
#!/bin/bash string="first second third fourth" IFS=' ' read -ra arr <<< "$string" echo "The last element is: ${arr[-1]}" |
1 2 3 |
The last element is: fourth |
The IFS
variable is used with a space delimiter to split the string in the above example. And the read
command is used with the -ra
option to read the input string into an array called arr
. Here, the -a
parameter tells the read
command to read the input into an array, and the -r
parameter tells it to treat backslashes as literal characters.
Then, the <<<
syntax is used to pass the input string as the input to the read
command. Finally, the ${arr[-1]}
is used to access the last element of the arr
array, the fourth
string.
Let"s see another example below:
1 2 3 4 5 6 |
#!/bin/bash string="first:second:third:fourth" IFS=':' read -ra arr <<< "$string" echo "The last element is: ${arr[-1]}" |
1 2 3 |
The last element is: fourth |
In this example, the last element of the string is extracted using the IFS
variable, which is set to a colon character ":"
. Splitting the string into words tells the shell to use a :
as the delimiter.
Without Using the IFS
variable
Use space as a delimiter to split the string in bash without the IFS
variable and get the last element.
1 2 3 4 5 6 |
#!/bin/bash string="first second third fourth" readarray -d " " -t words<<< "$string" echo "The last element is: ${words[-1]}" |
1 2 3 |
The last element is: fourth |
This code snippet split the string "first second third fourth"
into words using the readarray
command and stored them in an array called words
. Here, the -d
option specifies the space character as a delimiter, and the -t
parameter removes any trailing newlines. Next, the last element of a string is extracted from the words
array using ${words[-1]}
.
Let"s use any symbol as a delimiter other than a space character.
1 2 3 4 5 6 |
#!/bin/bash string="first@second@third@fourth" readarray -d "@" -t words<<< "$string" echo "The last element is: ${words[-1]}" |
1 2 3 |
The last element is: fourth |
In this example, the string is split into a words
array using the @
delimiter to extract the last element.
That’s all about bash split String and get last element.