Linux 如何在bash中提取子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16484972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:54:42  来源:igfitidea点击:

how to extract a substring in bash

linuxbashshell

提问by MOHAMED

I have the following string in bash with length > 4

我在bash中有以下字符串,长度> 4

str = "abcdefghijklmno"

and I want to extract into str2the 5 first charachter of str. So

我想提取到 . 的str2第 5 个字符中str。所以

str2="abcde"

How to do it with bash?

如何用 bash 做到这一点?

采纳答案by fedorqui 'SO stop harming'

Do use the expression

使用表达式

{string:position:length}

So in this case:

所以在这种情况下:

$ str="abcdefghijklm"
$ echo "${str:0:5}"
abcde

See other usages:

查看其他用法:

$ echo "${str:0}"      # default: start from the 0th position
abcdefghijklm
$ echo "${str:1:5}"    # start from the 1th and get 5 characters
bcdef
$ echo "${str:10:1}"   # start from 10th just one character
k
$ echo "${str:5}"      # start from 5th until the end
fghijklm

Taken from:
- wooledge.org - How can I use parameter expansion? How can I get substrings? How can I get a file without its extension, or get just a file's extension?
- Shell Command Language - 2.6.2 Parameter Expansion

来自
- wooledge.org -我如何使用参数扩展?我怎样才能得到子字符串?如何获取没有扩展名的文件,或者只获取文件的扩展名?
- Shell 命令语言 - 2.6.2 参数扩展