Today summarizes several ways to handle strings in the shell script, encapsulating several basic string-handling functions.
The code (STRING.INC) is as follows:
#!/bin/sh# a test function # input: No function str_testfunc () { echo "This is a test function"} #获取字符串长度 # Input: String function str_length () { echo ' expr length $1 '} #获取字符串子串 # Input: string Intercept Start position # Input: string intercept start position intercept length function str_substring () { if [ $# -eq 2 ]; then len= ' str_length $1 ' echo ' expr substr $1 $2 $len ' elif [ $# -eq 3 ]; then echo ' expr substr $1 $2 $3 ' else      ECHO    FI} #替换子串 # Input: string to replace substring string function for substitution str_replace () { echo ${1//$2/$3}} #按给定字符截取字符串 # Input: string character function for dividing substrings str_split () { i=1 while [ true ]; do temp= ' echo ' | cut -d ' $ -f$i ' if [ "$temp" != " ]; then ((i++)) echo $temp else break fi done} #删除字符串前后空格 # Input: String Function str_trim () { echo ' echo "'} #找出给定子串在字符串中出现的位置 # Input: string substring to search function str_indexof () { echo ' expr Index $1 $2 '} #将字符串中字符全部转换为大写 # Input: String Function str_toupper () { echo $ ( Echo $1 | tr ' [A-z] ' ' [A-z] ')} #将字符串中字符全部转换为小写 # Input: String function str_tolower () { echo $ (echo $1 | tr ' [A-z] ' ' [A-z] ')}
#!/bin/sh. ./string.incstr_testfunc# Get string length echo string "abcdefgh" Length: ' str_length "abcdefgh" ' "| END "#获取字符串子串echo string" abcdefgh "intercept substring: ' str_substring " abcdefgh " 4 3 '" | END "echo string" abcdefgh "intercept substring: ' str_substring " abcdefgh " 4 '" | END "#替换字符串echo replace BCD in ABCDEBCDF with F: ' str_replace " ABCDEBCDF " " BCD "x" ' "| END "#截取字符串echo intercept string 1: ' str_split ' a b c d e f g ' ' ' ' | END "echo intercept string 2: ' str_split " A:b:c:d:e:f:g " ": "" | END "#去掉前后空格echo " ab cd "remove front and back spaces: ' str_trim " ab cd "'" | END "BCDE first occurrence in ECHO ABCDEFG: ' str_indexof " ABCBCBD " " BCB "'" | END "#字符串中字母大小写转换echo ABCDEFGH" to capitalize: ' str_toupper "abcdefgh" ' "| END "echo " abcdefgh "Turn lowercase: ' str_tolower " abcdefgh "'" | END "Exit 0
Run:
END
Shell script: A summary of several basic string processing methods