Linux BASH tr 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11159043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
BASH tr command
提问by Dan
Id like to convert it to uppercase for the simple purpose of formatting so it will adhere to a future case statement. As I thought case statements are case sensitive.
为了格式化的简单目的,我想将其转换为大写,以便它遵守未来的 case 语句。因为我认为 case 语句区分大小写。
I see all over the place the tr command used in concert with echo commands to give you immediate results such as:
我到处都看到 tr 命令与 echo 命令一起使用,可以立即为您提供结果,例如:
echo "Enter in Location (i.e. SDD-134)"
read answer (user enters "cfg"
echo $answer | tr '[:lower:]' '[:upper:]' which produced
cfg # first echo not upper?
echo $answer #echo it again and it is now upper...
CFG
采纳答案by ghoti
This version doesn't require bash, but uses a pipe:
此版本不需要 bash,但使用管道:
read -p "Enter in Location (i.e. SDD-134) " answer
answer=$(echo "$answer" | tr '[:lower:]' '[:upper:]')
echo "$answer"
And if you're using bash and don't care about portability you can replace the second line with this:
如果您正在使用 bash 并且不关心可移植性,您可以将第二行替换为:
answer="${answer^^}"
Check the "Parameter Expansion" section of bash's man page for details.
有关详细信息,请查看 bash 手册页的“参数扩展”部分。
回答by Alex Howansky
Echoing a variable through tr will output the value, it won't change the value of the variable:
通过 tr 回显变量将输出值,它不会改变变量的值:
answer='cfg'
echo $answer | tr '[:lower:]' '[:upper:]'
# outputs uppercase but $answer is still lowercase
You need to reassign the variable if you want to refer to it later:
如果您想稍后引用它,则需要重新分配变量:
answer='cfg'
answer=$(echo $answer | tr '[:lower:]' '[:upper:]')
echo $answer
# $answer is now uppercase
回答by William Pursell
It is not clear what you are asking, but if you are trying to convert the user input to uppercase, just do:
不清楚您在问什么,但是如果您尝试将用户输入转换为大写,请执行以下操作:
sed 1q | tr '[:lower:]' '[:upper:]' | read answer
In shells that do not run the read in a subshell (eg zsh), this will work directly. To do this in bash, you need to do something like:
在不在子shell(例如zsh)中运行读取的shell 中,这将直接工作。要在 bash 中执行此操作,您需要执行以下操作:
printf "Enter in Location (i.e. SDD-134): "
sed 1q | tr '[:lower:]' '[:upper:]' | { read answer; echo $answer; }
After the subshell closes, answer
is an unset variable.
子shell关闭后,answer
是一个未设置的变量。
回答by xoid
good and clear way to uppercase variable is
大写变量的好方法是
$var=`echo $var|tr '[:lower:]' '[:upper:]'`
Note Bene a back quotes
注意 Bene 反引号
回答by chepner
In bash
version 4 or greater:
在bash
版本 4 或更高版本中:
answer=${answer^^*}