bash 截取字符串

Posted on Posted in command

在 Bash 中抽取子字符串

## 格式 ## 
${parameter:offset:length} 
## 定义变量 u ##
u="this is a test"
var="${u:10:4}"
echo "${var}" # test , 10 : 偏移位置  4 : 长度

使用 IFS

u="this is a test"
set -- $u
echo "$1" # this
echo "$2" # is
echo "$3" # a
echo "$4" # test

借助 cut 命令

u="this is a test"
echo "$u" | cut -d' ' -f 4
echo "$u" | cut --delimiter=' ' --fields=4
##########################################
## WHERE
##   -d' ' : Use a whitespace as delimiter
##   -f 4  : Select only 4th field
##########################################
var="$(cut -d' ' -f 4 <<< $u)"
echo "${var}"
» 转载请注明来源:若我若鱼 » bash 截取字符串

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + twelve =