需要在一定数量的字符后在 bash 中拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10757300/
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
Need to split a string in bash after certain number of characters
提问by howtechstuffworks
I am writing a bash script that will execute a command and store the value in a string variable, now I need to split the string after certain characters. Is there a way? I cannot use delimiters coz the format is kinda like this
我正在编写一个 bash 脚本,该脚本将执行命令并将值存储在字符串变量中,现在我需要在某些字符后拆分字符串。有办法吗?我不能使用分隔符,因为格式有点像这样
PV Name /dev/sda2
PV Size 10.39 GB
Here I need to get the /dev/sda2 and 10.39 GB(if possible, just 10.39 alone) and write it in a new file. I cannot use delimiter because the space is at first.. I have not done much bash scripting. Is there a way to do this?
在这里,我需要获取 /dev/sda2 和 10.39 GB(如果可能,只有 10.39)并将其写入新文件中。我不能使用分隔符,因为空间是一开始..我没有做过很多 bash 脚本。有没有办法做到这一点?
采纳答案by Paused until further notice.
echo "${var:8}"
will echo the contents of $varstarting at the character 8 (zero-based).
将回显$var从字符 8 开始的内容(从零开始)。
To strip off anything starting at the first space:
从第一个空格开始剥离任何内容:
data=${var:8}
echo "${data%% *}"
回答by aland
To get only certain characters, use cut:
要仅获取某些字符,请使用cut:
$ echo '1234567' | cut -c2-5
2345
However, in your case awklooks like better option:
但是,在您的情况下awk看起来是更好的选择:
$ echo ' PV Size 10.39 GB' | awk '{ print }'
10.39
It reads text as space/tab separated columns, so it should work perfectly fine
它将文本读取为空格/制表符分隔的列,因此它应该可以正常工作

