Problem Statement
Explain string manipulation in bash including concatenation, substring extraction, pattern matching, and replacement.
Explanation
String concatenation: simply place strings together: STR="$VAR1$VAR2" or STR="${VAR1}text${VAR2}". No special operator needed. Append to string: STR="$STR more text" or STR+=" more text" (bash-specific). Quotes handle spaces: STR="$VAR1 $VAR2" includes space.
String length: ${#VAR} returns length. Example: VAR="hello"; echo ${#VAR} outputs 5. Useful for validation: if [ ${#INPUT} -lt 3 ]; then echo "Too short"; fi.
Substring extraction: ${VAR:offset:length} extracts substring. VAR="hello world"; ${VAR:0:5} gives "hello", ${VAR:6} gives "world" (from position 6 to end), ${VAR: -5} gives "world" (last 5 chars, note space before -). Offset 0-indexed.
Pattern matching and removal: ${VAR#pattern} removes shortest match from beginning, ${VAR##pattern} removes longest match from beginning, ${VAR%pattern} removes shortest match from end, ${VAR%%pattern} removes longest match from end. Example: FILE="path/to/file.txt"; ${FILE##*/} gives "file.txt" (basename), ${FILE%.*} gives "path/to/file" (remove extension).
String replacement: ${VAR/pattern/replacement} replaces first match, ${VAR//pattern/replacement} replaces all matches. Example: PATH="/home/user"; ${PATH/home/opt} gives "/opt/user". Case conversion (bash 4+): ${VAR^} uppercases first char, ${VAR^^} uppercases all, ${VAR,} lowercases first, ${VAR,,} lowercases all.
Default values: ${VAR:-default} returns default if VAR unset/empty, ${VAR:=default} assigns default if unset/empty, ${VAR:?error} exits with error if unset/empty. Example: OUTPUT=${1:-output.txt} uses first arg or default. Understanding string operations enables text processing without external commands like sed or awk.