未加星标

How do I convert this code to shell script?

字体大小 | |
[系统(linux) 所属分类 系统(linux) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

I'm writing a program that can convert uppercase into lowercase and lowercase into uppercase alternatively. Here are some examples.

abcde -> aBcDe ABCDE -> aBcDe abCdE -> aBcDe

I know how to make it in c but not shell script. Here's the c code.

1 #include <stdio.h> 2 #include <ctype.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 int main(int args, char* argv[]) 7 { 8 9 if(args != 2) 10 exit(1); 11 char buf[100]; 12 for(int i = 0; i < strlen(argv[1]); i++) 13 { 14 if(i%2 == 0) 15 buf[i] = tolower(argv[1][i]); 16 else 17 buf[i] = toupper(argv[1][i]); 18 } 19 printf("%s\n", buf); 20 }

Can you guys help me how to write it in shell script? Thank you.

With sed you can repeatedly parse 2 chars, changing the first in lowercase and the second in uppercase. That seems nice, but how about the last character with a string with an odd number of chars?

First change the last char to lowercase. That is OK for an odd length string, and will be modified with the second command for an even length string:

if [ $# -ne 1 ]; then exit 1 fi lastcharlow=$(sed -r "s/(.)$/\l\1/" <<< "${1}") sed -r "s/(.)(.)/\l\1\u\2/g" <<<"${lastcharlow}"

The last 2 lines can be combined:

sed -r "s/(.)$/\l\1/; s/(.)(.)/\l\1\u\2/g" <<<"${1}" EDIT: Text beneath

The sed solution is nice and short, but doesn't show how to loop through a string. When you really don't know a tool working for you, you can loop through your string. I will show 3 methods for changing the case of a char and two functions for looping through a string.

function upper { # tr '[:lower:]' '[:upper:]' <<< $1 # echo "${1^^}" typeset -u up; up="$1"; echo "${up}" } function lower { # tr '[:upper:]' '[:lower:]' <<< $1 # echo "${1,,}" typeset -l low; low="$1"; echo "${low}" } function grepsolution { i=0 while read -r onechar; do (( i++ )) if [[ $((i%2)) = 0 ]] ; then printf "%s" $(upper "${onechar}" ) else printf "%s" $(lower "${onechar}" ) fi done < <(echo $1 | grep -o .) printf "\n" } function substr_solution { i=0 while [ $i -lt ${#1} ]; do (( i++ )) if [[ $((i%2)) = 0 ]] ; then printf "%s" $(upper "${1:i-1:1}" ) else printf "%s" $(lower "${1:i-1:1}" ) fi done printf "\n" } for teststring in abcde abcdef ABCDE ABCDEF; do echo "Converting ${teststring}" printf "%-20s: " "grepsolution" grepsolution "${teststring}" printf "%-20s: " "substr_solution" substr_solution "${teststring}" done

本文系统(linux)相关术语:linux系统 鸟哥的linux私房菜 linux命令大全 linux操作系统

代码区博客精选文章
分页:12
转载请注明
本文标题:How do I convert this code to shell script&amp;quest;
本站链接:https://www.codesec.net/view/610716.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 系统(linux) | 评论(0) | 阅读(68)