如何在 bash 中的变量中只保留三个字母
How to keep only three letters in a variable in bash
我正在接受用户输入 $1,要求约会。人们无法使用帮助页面,所以我在通过 grep 传递它时不得不将其简化。
我的输入是 Day-Mon-Year - 其中日前面没有 0,月份只有 3 个字母。
除了第 3 个字母 'cut-down.'
我什么都做完了
## stripping leading zero, turning words to lower-case & then capitalizing only the first letter ##
fdate=$(echo | sed 's/^0//g' | tr '[:upper:]' '[:lower:]' | sed -e "s/\b\(.\)/\u/g")
任何人都可以帮我以 "August," 为例,并在这个单一变量中将其缩减到 Aug 吗?或者也许是另一种方式?我对任何事情都持开放态度。
提前致谢!
您可以在 bash 中执行此操作,无需外部命令:
a='0heLLo wOrld'
a=${a#0} # Remove leading 0. Change to ${a##0} to remove multiply zeros
a="${a:0:3}" # Take 3 first characters
a=${a,,} # Lowercase
a=${a^} # Uppercase first
printf "%s\n" "$a" # Hel
或者,它可以在一个 sed
命令中完成:
% sed 's/^0//;s/\(.\)\(..\).*/\u\L/' <<< "0heLLo wOrld"
Hel
细分
s/^0//; # Remove leading 0. Change to 's/^0*//' to remove multiply zeros
s/
\(.\)\(..\) # Capture first character in and next two in
.* # Match rest of string
/\u\L/ # Uppercase and lowercase
我正在接受用户输入 $1,要求约会。人们无法使用帮助页面,所以我在通过 grep 传递它时不得不将其简化。
我的输入是 Day-Mon-Year - 其中日前面没有 0,月份只有 3 个字母。
除了第 3 个字母 'cut-down.'
我什么都做完了## stripping leading zero, turning words to lower-case & then capitalizing only the first letter ##
fdate=$(echo | sed 's/^0//g' | tr '[:upper:]' '[:lower:]' | sed -e "s/\b\(.\)/\u/g")
任何人都可以帮我以 "August," 为例,并在这个单一变量中将其缩减到 Aug 吗?或者也许是另一种方式?我对任何事情都持开放态度。
提前致谢!
您可以在 bash 中执行此操作,无需外部命令:
a='0heLLo wOrld'
a=${a#0} # Remove leading 0. Change to ${a##0} to remove multiply zeros
a="${a:0:3}" # Take 3 first characters
a=${a,,} # Lowercase
a=${a^} # Uppercase first
printf "%s\n" "$a" # Hel
或者,它可以在一个 sed
命令中完成:
% sed 's/^0//;s/\(.\)\(..\).*/\u\L/' <<< "0heLLo wOrld"
Hel
细分
s/^0//; # Remove leading 0. Change to 's/^0*//' to remove multiply zeros
s/
\(.\)\(..\) # Capture first character in and next two in
.* # Match rest of string
/\u\L/ # Uppercase and lowercase