bash 脚本将大写字母转换为小写字母,反之亦然

bash 脚本将大写字母转换为小写字母,反之亦然

请检查并建议我的脚本。我正在尝试获取一个单词(最少 2 个,最多 5 个字符)作为其输入。

用户将提供字符位置,然后脚本会将其从小写更改为大写或大写更改为小写。以下是迄今为止不完整的脚本:

输入:teSt 3

输出: test

#!/bin/bash
clear
while true
do
echo ******TEST*****
read -p 'Enter a word :' word
if [[ ${#word} -le 1 ]] || [[ ${#word} -ge 6 ]]; then
   echo "Invalid input (Min of 2 and max of 5)!."
   exit 1

fi
echo ${word^^*}
done

答案1

#!/bin/bash

read -p 'Enter a word : ' str id

if [[ ${#str} -le 1 ]] || [[ ${#str} -ge 6 ]]; then
   echo "Invalid input (Min of 2 and max of 5)!." && exit 1

idt=$((id-1))

case ${str:idt:1} in
    [[:lower:]]) 
            r='\U';
        ;;
    [[:upper:]])
            r='\L';
        ;;
esac

echo $str | sed -r "s/./$r&/$id"

$ ./script.sh
Enter a word : test 1
Test
$ ./script.sh
Enter a word : Test 2
TEst
$ ./script.sh
Enter a word : teST 3
tesT

答案2

您可以使用 ~ 切换大写和小写,

检查这个:

#!/bin/bash
clear
while true
do
echo ******TEST*****
read -p 'Enter a word :' word pos
if [[ ${#word} -le 1 ]] || [[ ${#word} -ge 6 ]]; then
   printf "\n\tInvalid input (Min of 2 and max of 5)!.\n\n"
fi

for x in  `seq 0 ${#word}`; do
    c=${word:$x:1}
    if [ "$x" -eq "$(($pos-1))" ]; then
        printf "%s" "${c~}"
    else
        printf "%s" "${c}"
    fi
done
printf "\n\n"
done

答案3

该脚本仅切换指定字母的大小写。它不验证输入。

#!/bin/bash

while read -r -p "Enter a word :" word position; do
    sed -r "s/([a-z])|([A-Z])/\U\1\L\2/${position}" <<< "$word"
done    

测试:

$ ./up_and_low_case.sh 
Enter a word :CAT 2
CaT
Enter a word :rabbit 4
rabBit

相关内容