什么 linux shell 命令返回字符串的一部分?
我想找到一个可以返回部分字符串的linux命令。 在大多数编程语言中,它是 substr()
函数。 bash 是否有任何可用于此目的的命令。 我希望能够做这样的事情...... substr "abcdefg" 2 3
- 打印cde
。
随后的类似问题:
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:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您正在寻找一个 shell 实用程序来执行类似的操作,您可以使用
cut
命令。举个例子,尝试:
它产生
Where
-cN-M
告诉cut命令返回列N
到M
,包括在内。If you are looking for a shell utility to do something like that, you can use the
cut
command.To take your example, try:
which yields
Where
-cN-M
tells the cut command to return columnsN
toM
, inclusive.来自 bash 联机帮助页:
或者,如果您不确定是否有
bash
,请考虑使用cut
。From the bash manpage:
Or, if you are not sure of having
bash
, consider usingcut
.在“纯”bash 中,您有许多用于(子)字符串操作的工具,主要但不限于 参数扩展:
索引子字符串扩展(具有负偏移量的特殊行为,以及在较新的 Bashes 中,负长度):
当然,对参数是否为 null 进行操作的非常有用的扩展:
它们比那些具有更多可调整的行为正如我所说,还有其他方法来操作字符串(常见的一种是
$(command replacement)
与 sed 或任何其他外部过滤器相结合)。 但是,通过输入 man bash 很容易找到它们,因此我认为没有必要进一步扩展这篇文章。In "pure" bash you have many tools for (sub)string manipulation, mainly, but not exclusively in parameter expansion :
Indexed substring expansion (special behaviours with negative offsets, and, in newer Bashes, negative lengths):
And of course, the much useful expansions that operate on whether the parameter 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 typingman bash
that I don't feel it merits to further extend this post.在 bash 中,您可以尝试以下操作:
Linux 文档项目中的更多示例
In bash you can try this:
More samples in The Linux Documentation Project
expr(1)
有一个 substr 子命令:如果您没有 bash(可能是嵌入式 Linux)并且您不希望需要使用 cut( 1).
expr(1)
has a substr subcommand: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).