什么 linuxshell 命令返回字符串的一部分?

我想找到一个可以返回字符串一部分的 linux 命令。在大多数编程语言中,它是 substr()函数。Bash 是否有任何可用于此目的的命令。我想做这样的事。 指纹 cde


接下来的类似问题:

241152 次浏览

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.

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

${string:position:length}

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.

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).

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.