What linux shell command returns a part of a string?
LinuxStringBashSubstrLinux Problem Overview
I want to find a linux command that can return a part of the string. In most programming languages, it's the substr()
function. Does bash have any command that can be used for this purpose. I want to be able to do something like this...
substr "abcdefg" 2 3
- prints cde
.
Subsequent similar question:
Linux Solutions
Solution 1 - Linux
If you are looking for a shell utility to do something like that, you can use the cut
command.
To take your example, try:
echo "abcdefg" | cut -c3-5
which yields
cde
Where -cN-M
tells the cut command to return columns N
to M
, inclusive.
Solution 2 - Linux
From the bash manpage:
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset.
[...]
Or, if you are not sure of having bash
, consider using cut
.
Solution 3 - Linux
In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :
${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}
Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):
${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}
And of course, the much useful expansions that operate on whether the parameter is null:
${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}
They have more tweakable behaviours than those listed, and as I said, there are other ways to manipulate strings (a common one being $(command substitution)
combined with sed or any other external filter). But, they are so easily found by typing man bash
that I don't feel it merits to further extend this post.
Solution 4 - Linux
In bash you can try this:
stringZ=abcABC123ABCabc
# 0123456789.....
# 0-based indexing.
echo ${stringZ:0:2} # prints ab
More samples in [The Linux Documentation Project][1]
[1]: http://tldp.org/LDP/abs/html/string-manipulation.html "here"
Solution 5 - Linux
${string:position:length}
Solution 6 - Linux
expr(1)
has a substr subcommand:
expr substr <string> <start-index> <length>
This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).