简体   繁体   English

如何在一个回显中大写和替换 shell 脚本中的字符

[英]How to capitalize and replace characters in shell script in one echo

I am trying to find a way to capitalize and replace dashes of a string in one echo.我正在尝试找到一种方法来在一个回声中大写和替换字符串的破折号。 I do not have the ability to use multiple lines for reassigning the string value.我无法使用多行来重新分配字符串值。

For example: string='test-e2e-uber' needs to echo $string as TEST_E2E_UBER例如: string='test-e2e-uber'需要将echo $string显为TEST_E2E_UBER

I currently can do one or the other by utilizing我目前可以通过利用来做一个或另一个

${string^^} for capitalization ${string^^}用于大写

${string//-/_} for replacement ${string//-/_}用于替换

However, when I try to combine them it does not appear to work (bad substitution error).但是,当我尝试将它们组合起来时,它似乎不起作用(替换错误)。 Is there a correct syntax to achieve this?是否有正确的语法来实现这一点?

echo ${string^^//-/_}

This does not answer directly your question, but still following script achieves what you wanted:这不会直接回答您的问题,但仍然遵循脚本可以实现您想要的:

declare -u string='test-e2e-uber'
echo ${string//-/_}

Why do you dislike it so much to have two successive assignment statements?为什么你这么不喜欢有两个连续的赋值语句? If you really hate it, you will have to revert to some external program to do the task for you, such as如果你真的讨厌它,你将不得不恢复到一些外部程序来为你完成任务,例如

string=$(tr  a-z- A-Z_ <<<$string)

but I would consider it a waste of resources to create a child process for such a simple operation.但是我认为为这样一个简单的操作创建一个子进程是一种资源浪费。

  1. You can do that directly with the 'tr' command, in just one 'echo'您可以直接使用“tr”命令执行此操作,只需一个“echo”
echo "$string" | tr "-" "_" | tr "[:lower:]" "[:upper:]"
TEST_E2E_UBER

I don't think 'tr' allows to do the conversion of 2 objects in one command only, so I used pipe for output redirection我不认为 'tr' 只允许在一个命令中转换 2 个对象,所以我使用 pipe 进行 output 重定向

  1. or you could do something similar with 'awk'或者你可以用'awk'做类似的事情
echo "$string" | awk '{gsub("-","_",$0)} {print toupper($0)}'
TEST_E2E_UBER

in this case, I'm replacing with 'gsub' the hyphen, then i'm printing the whole record to uppercase在这种情况下,我将用“gsub”替换连字符,然后将整个记录打印为大写

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM