如何在Bash 4中将变量每个单词首字母大写、其余字母小写?
How to Capitalize First Letter of Each Word (Rest Lowercase) in Bash 4
Great questions! Bash 4 introduced some really handy parameter expansion tools for case manipulation, so we can handle both your scenarios cleanly. Let’s break them down step by step:
1. Convert Every Word in a Text File/Input Stream
If you’re working with a text file or piped input, you can use Bash’s built-in case conversion alongside a loop to process each line and word individually:
# Process lines from input.txt and output converted text while read -r line; do converted_line="" # Split the line into individual words for word in $line; do # First convert the entire word to lowercase lower_word="${word,,}" # Then capitalize the first character capitalized_word="${lower_word^}" # Build the converted line converted_line+="$capitalized_word " done # Trim the trailing space and print the result echo "${converted_line% }" done < input.txt
If you prefer a more concise one-liner, awk works great here too (and it’s compatible across older Bash versions):
awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2)); print}' input.txt
2. Convert a Bash Variable’s Words to Title Case
For a single variable, the approach is similar—split the variable into words, process each one, then reassemble the result:
# Example variable with mixed case formatting original_var="hELLO wORLD tEST" converted_var="" for word in $original_var; do # Convert the word to full lowercase, then capitalize the first letter processed_word="${word,,}" processed_word="${processed_word^}" converted_var+="$processed_word " done # Remove the trailing space and assign the final result converted_var="${converted_var% }" echo "$converted_var" # Output: Hello World Test
For a shorter variable-focused solution, pipe the variable content to awk:
original_var="hELLO wORLD tEST" converted_var=$(echo "$original_var" | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2)); print}') echo "$converted_var"
Quick Notes:
${var,,}: A Bash 4+ feature that converts all characters invarto lowercase.${var^}: Another Bash 4+ feature that capitalizes the first character ofvar.- By default, Bash splits words using whitespace—if your words include special characters, you may need to adjust the
IFS(Internal Field Separator) variable to match your specific use case.
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

