我使用下面的 bash 脚本来分割字符串:
string='/dev/shm: 0%used(0MB/4003MB) /var/spool/site/storage/users: 64%used(64437MB/100760MB) /run/user/1001: 0%used(0MB/801MB) /run: 10%used(165MB/1601MB) /run/lock: 0%used(0MB/5MB) /run/user/112: 0%used(0MB/801MB) /sys/fs/cgroup: 0%used(0MB/4003MB) /: 80%used(40518MB/50364MB) (>80%) : WARNING '
IFS=' /' # delimit on [SPACE]/
set -f # disable the glob part
array=($string) # invoke the split+glob operator
for i in "${array[@]}"; do echo '/'$i; done
字符串基于space
or进行分割/
。我想要实现的是,当字面上存在两个字符串[space]/
而不是每个字符串单独存在时,将字符串分开。
答案1
您可以使用awk
并指定' /'
作为分隔符:
$ cat data
/dev/shm: 0%used(0MB/4003MB) /var/spool/site/storage/users: 64%used(64437MB/100760MB) /run/user/1001: 0%used(0MB/801MB) /run: 10%used(165MB/1601MB) /run/lock: 0%used(0MB/5MB) /run/user/112: 0%used(0MB/801MB) /sys/fs/cgroup: 0%used(0MB/4003MB) /: 80%used(40518MB/50364MB) (>80%) : WARNING
$ cat data | awk -F' /' '{for(i=1;i<=NF;i++){print $i}}'
/dev/shm: 0%used(0MB/4003MB)
var/spool/site/storage/users: 64%used(64437MB/100760MB)
run/user/1001: 0%used(0MB/801MB)
run: 10%used(165MB/1601MB)
run/lock: 0%used(0MB/5MB)
run/user/112: 0%used(0MB/801MB)
sys/fs/cgroup: 0%used(0MB/4003MB)
: 80%used(40518MB/50364MB) (>80%) : WARNING
参见这篇文章:https://stackoverflow.com/questions/23114583/bash-script-split-string-using-regex-delimiter