Skip to main content

String Manipulation 字串處理

字串長度
my_string="abhishek"
echo "length is ${#my_string}"

Using expr

str="my string"
length=$(expr length "$str")
echo "Length of my string is $length"

Using awk

echo "my string" | awk '{print length}'

Using wc

str="my string"
length=$(echo -n "my string" | wc -m)
echo "Length of my string is $length"
字串比對

Using wildcards

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'
if [[ "$STR" == *"$SUB"* ]]; then
  echo "It's there."
fi

Using case

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'

case $STR in

  *"$SUB"*)
    echo -n "It's there."
    ;;
esac

Using Regex

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'

if [[ "$STR" =~ .*"$SUB".* ]]; then
  echo "It's there."
fi

Using Grep

#!/bin/bash

STR='GNU/Linux is an operating system'
SUB='Linux'

if grep -q "$SUB" <<< "$STR"; then
  echo "It's there"
fi
字串合併
str1="hand"
str2="book"
str3=$str1$str2
字元提取
foss="Fedora is a free operating system"
echo ${foss:0:6}
字元取代
foss="Fedora is a free operating system"
echo ${foss/Fedora/Ubuntu}
Summary: String Manipulation and Expanding Variables
${parameter:-defaultValue} Get default shell variables value ${parameter:=defaultValue} Set default shell variables value ${parameter:?"Error Message"} Display an error message if parameter is not set ${#var} Find the length of the string ${var%pattern} Remove from shortest rear (end) pattern ${var%%pattern} Remove from longest rear (end) pattern ${var:num1:num2} Substring ${var#pattern} Remove from shortest front pattern ${var##pattern} Remove from longest front pattern ${var/pattern/string} Find and replace (only replace first occurrence) ${var//pattern/string} Find and replace all occurrences ${!prefix*} Expands to the names of variables whose names begin with prefix.

${var,}

${var,pattern}

Convert first character to lowercase.

${var,,}

${var,,pattern}

Convert all characters to lowercase.

${var^}

${var^pattern}

Convert first character to uppercase.

${var^^}

${var^^pattern}

Convert all character to uppercase.