KSH - String Operaters

本文介绍Shell脚本中字符串的各种操作方法,包括获取长度、子串提取、替换等实用技巧,并展示了如何通过变量扩展格式实现这些功能。

Get length

${#str}

Get sub-string

${str:0:3}           #start-pos, length
${str:1}             #start-pos


For example

#!/bin/ksh

STR="12345678"

echo ${STR:0:2}         # get first 2: 12
echo ${STR#${STR%??}}   # get last 2 : 78

echo ${STR:2}           # cut first 2: 345678
echo ${STR%??}          # cut last 2 : 123456

Variable Expansion Formats

${variable:-word}

value of variable if set and not null, else print word

${variable:=word}

value of variable if set and not null, else variable is set to word , then expanded

${variable:+word}

value of word if variable is set and not null, else nothing is substituted

${variable:?word}

value of variable if set and not null, else print value of word and exit

${variable#pattern}

value of variable without the smallest beginning portion that matches  pattern

${variable##pattern}

value of variable without the largest beginning portion that matches pattern

For example


  • PROGRAM=${0##*/}        # get the program name, strip the path
  • FILE=${1##*/}           # get the file name of first parm, strip the path


${variable%pattern}

value of variable without the smallest ending portion that matches pattern

${variable%%pattern}

value of variable without the largest ending portion that matches pattern

${variable//pattern1/pattern2}

replace all occurrences of pattern1 with pattern2 in variable


Delete sub-string

${var%%A*}     # delete all chars at the right of first char ‘A’;         “12A34A56” => “12”
${var%A*}         # delete all chars at the right of last char ‘A’;         “12A34A56” => “12A34”

${var##A*}       # delete all chars at the left of last char ‘A’;   “12A34A56” => “56”
${var#A*}          # delete all chars at the left of first char ‘A’;   “12A34A56” => “34A67”

Replace sub-string

${var/A/B}        # replace first ‘A’ with ‘B’;       “12A34A56” => “12B34A56”

${var//A/B}       # replace all ‘A’ with ‘B’; “12A34A56” => “12B34B56”

String starts/ends with a sub-string

AA="ABCD"
BB="EFGH"
CC="AB"
DD="GH"

[[ "${AA}" =~ "^AB" ]] && echo "YES" || echo "NO"   # ${AA} starts with "AB": Y
[[ "${BB}" =~ "^AB" ]] && echo "YES" || echo "NO"   # ${BB} starts with "AB": N
[[ "${AA}" =~ "CD$" ]] && echo "YES" || echo "NO"   # ${AA} ends with "CD": Y
[[ "${BB}" =~ "CD$" ]] && echo "YES" || echo "NO"   # ${AA} ends with "CD": N

[[ "${AA}" =~ "^${CC}" ]] && echo "YES" || echo "NO"    # ${AA} starts with ${CC}: Y
[[ "${AA}" =~ "^${DD}" ]] && echo "YES" || echo "NO"    # ${AA} starts with ${DD}: N
[[ "${BB}" =~ "${CC}$" ]] && echo "YES" || echo "NO"    # ${AA} ends with ${CC}: N
[[ "${BB}" =~ "${DD}$" ]] && echo "YES" || echo "NO"    # ${AA} ends with ${DD}: Y

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值