在 bash 脚本中使用“tr”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26945958/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:48:06  来源:igfitidea点击:

Working with 'tr' in bash script

bash

提问by tilefrae

How can I work with tr '[a-z]' '[A-Z]'in Bash script?

如何tr '[a-z]' '[A-Z]'在 Bash 脚本中使用?

I want save $1to a text file using tr '[a-z]' '[A-Z]'and print to console.

我想使用保存$1到文本文件tr '[a-z]' '[A-Z]'并打印到控制台。

How can I do this?

我怎样才能做到这一点?

#!/bin/bash  
echo  | tr '[a-z]' '[A-Z]'
exit 0

is not working.

不管用。

采纳答案by Junior Dussouillez

You can use the command tee.

您可以使用命令tee

Example :

例子 :

echo "AbC" | tr '[a-z]' '[A-Z]' | tee output.txt

It will print ABCin the terminal and in a file (output.txt)

它将ABC在终端和文件 (output.txt) 中打印

回答by gniourf_gniourf

With Bash≥4, you don't need to trto convert to upper case since you can use parameter expansions: ${var^^}will expand to the uppercase expansion of var.

使用 Bash≥4,您不需要tr转换为大写,因为您可以使用参数扩展:${var^^}将扩展为var.

#!/bin/bash

# Convert first argument to upper case and save in variable upper1
upper1=${1^^}

# print to console:
printf '%s\n' "$upper1"

# and save to file
printf > file.txt '%s\n' "$upper1"

All this is done in pure Bash with no external tools. Also, there are no pipes and subshells needed.

所有这些都是在纯 Bash 中完成的,没有外部工具。此外,不需要管道和子壳。