Shell 字符串相关操作

 
Category: Linux-Shell

写在前面

字符串创建

# 等号两边不能加空格!
s1="abc"
s2=abc
s3='abc'
# 作为判断的话 = 两边必须加空格
[[ $s1 = $s2 && $s2 = $s3 ]] && echo yes

单引号不会解释变量, 双引号会

例如

  $ t2="$s1=abc"; echo $t2
  abc=abc
  $ t1='$s1=abc'; echo $t1
  $s1=abc

子字符串

#!/bin/bash

name="helloworld"

[[ ${name} = "helloworld" ]] && echo yes || echo no
[[ ${#name} = 10 ]] && echo yes || echo no
[[ ${name:4} = "oworld" ]] && echo yes || echo no
[[ ${name:3:5} = "lowor" ]] && echo yes || echo no

echo "匹配"
# Substring matching: In Bash, the shortest and longest possible match of a substring can be found and deleted from either front or back.
: '
To delete the shortest substring match from front of $string:
${string#substring}

To delete the shortest substring match from back of $string:
${string%substring}

To delete the longest substring match from front of $string:
${string##substring}

To delete the longest substring match from back of $string:
${string%%substring}
'
# just for truncate
[[ ${name#he*l} = "loworld" ]] && echo yes || echo no
[[ ${name##he*l} = "d" ]] && echo yes || echo no

# 匹配以 he*l 结尾的字符串, 并删掉模式串匹配的部分
[[ ${name%he*l} = "helloworld" ]] && echo yes || echo no
[[ ${name%%he*l} = "helloworld" ]] && echo yes || echo no

#
[[ ${name%l*d} = "hellowor" ]] && echo yes || echo no
[[ ${name%%l*d} = "he" ]] && echo yes || echo no

echo "替换字符串"

[[ ${name/world/ all of the world!} = "hello all of the world!" ]] && echo yes || echo no
[[ ${name//l/L} = "heLLoworLd" ]] && echo yes || echo no

操作

合并

直接合并, 特殊字符需要转义, 要不然会被识别为命令参数

s1=hello
s2=world
ans=$s1\ $s2
[[ $ans = "hello world" ]] && echo yes

常见的操作就是export PATH="/bin:$PATH"