简体   繁体   English

如何将bash变量全部改为小写sed

[英]How to change all bash variables to lowercase in sed

I have hundreds of bash scripts that have upper case variables like so我有数百个 bash 脚本,它们具有像这样的大写变量

#!/bin/bash

FOO=bar
RED=blue
UP=down

I am making them lower case like so我像这样把它们变成小写

for var in FOO RED UP
do
    grep -rl '\<$var\>' | xargs sed -i 's/\<$var\>/$(echo "$var" | tr '[:upper:]' '[:lower:]')/g"
done

Now I have encountered files with hundreds of variable declerations and it is becoming too difficult to copy paste each one.现在我遇到了有数百个变量 declerations 的文件,并且复制粘贴每个文件变得太困难了。 I tried automating the process like so我试过像这样自动化这个过程

grep -rl '\w*=[^=]' | xargs sed -E "s/(\w*)=([^=])/$(echo \1 | tr '[:upper:]' '[:lower:]')=\2/g"

But the problem lies in $(echo \1...) which obviously will fail但问题在于$(echo \1...)显然会失败

Is there a way to quickly find all vars and convert to lowercase using regex?有没有办法快速找到所有变量并使用正则表达式转换为小写?

EDIT:编辑:

As requested, assume we have 1 file like so根据要求,假设我们有 1 个这样的文件

#!/bin/bash

AAA="hello world"
AAB="hello world"
...
ZZZ="hello world"

And assume I have a large number (>10000) nested (in directories or sub-directories) like so并假设我有大量(> 10000)嵌套(在目录或子目录中)像这样

#!/bin/bash

echo $AAA
echo $AAB
...
echo $ZZZ
if [ $AAA == "foo" ]
then
    #do something
fi

I want to search for any assignments ( \w*=[!=] ) and then do a word replace on that variable to make it lower case.我想搜索任何赋值( \w*=[!=] ),然后对该变量进行单词替换以使其小写。 Note the if condition, I through that in there to show that there may be a case of a word followed by 2 equations, but we are matching for only 1 equation (and no space)注意if条件,我通过那里的那个来表明可能存在一个单词后跟 2 个等式的情况,但我们只匹配 1 个等式(没有空格)

Edit 2: Note that I want only the variable names to be converted to lower case, not everything编辑 2:请注意,我只想将变量名转换为小写,而不是所有的

# Current Input
SOME_VAR="Humpty Dumpty had a great FALL"

# Desired Output
some_var="Humpty Dumpty had a great FALL"

The only solution that worked for me was to go through and replace the variable names to lower case in three steps唯一对我有用的解决方案是 go 通过三个步骤将变量名替换为小写

 # Change all SOME_VAR=... to some_var=...                                 
 grep -rl '\w\+=' | xargs sed -i 's/\w\+=/\L&/g'                             
                                                                             
 # Change all $SOME_VAR to $some_var                                         
 grep -rl '$\w\+' | xargs sed -i 's/$\w\+/\L&/g'                             
                                                                             
 # Change all ${SOME_VAR} to ${some_var}                                     
 grep -rl '$\w\+' | xargs sed -i 's/${\w\+}/\L&/g'

Then I went back and changed the few environment variables back to upper case然后我回去把几个环境变量改回大写

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

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