@xtccc
2018-05-09T14:41:35.000000Z
字数 1222
阅读 1945
Shell
目录
#!/bin/bash
str="hello.world.hello.shell"
IFS="."
arr=($str)
for i in "${!arr[@]}"; do
token=${arr[$i]}
echo "$i $token";
done
运行结果:
按照多字符切分字符串不能通过设置IFS
来实现
########################################
## https://www.tutorialkart.com/bash-shell-scripting/bash-split-string/
## 对str按照delimiter进行切分
## 返回第index个token (index从0开始)
#########################################
split() {
local str="$1"
local delimiter="$2"
local index="$3"
local s=$str$delimiter
array=();
while [[ $s ]]; do
array+=( "${s%%"$delimiter"*}" );
s=${s#*"$delimiter"};
done;
# declare -p array
# echo $index
echo ${array[$index]}
}
result=$(split "LearnABCtoABCSplitABCaABCString" "ABC" 2)
echo $result
例如,对于free命令:
tao@cas-01-prod:~/tao$ free
total used free shared buffers cached
Mem: 15404784 15317124 87660 0 6696 6663804
-/+ buffers/cache: 8646624 6758160
Swap: 0 0 0
如果只想保留输出的第3行:
tao@cas-01-prod:~/tao$ free | sed -n 3p
-/+ buffers/cache: 8646200 6758584
如果只想保留它输出的第2~3行:
tao@cas-01-prod:~/tao$ free | sed -n 2,3p
Mem: 15404784 15331088 73696 0 6696 6678736
-/+ buffers/cache: 8645656 6759128
如果想保留第1行、第4行:
tao@cas-01-prod:~/tao$ free | sed -n -e 1p -e 4p
total used free shared buffers cached
Swap: 0 0 0