I have hundreds of bash scripts that have upper case variables like so
#!/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. 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
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
#!/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
#!/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. 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)
Edit 2: Note that I want only the variable names to be converted to lower case, not everything
# 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
# 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.