0

I have a list of words and I want to make one character lowercase and one character uppercase. For example, the word information I want to be iNfOrMaTiOn and InFoRmAtIoN

3 Answers 3

4

GNU sed approach:

-- starting with a lowercase letter:

s="information" sed 's/\(.\)\(.\)/\L\1\U\2/g' <<< $s iNfOrMaTiOn 

-- starting with an uppercase letter:

s="information" sed -E 's/(.)(.){,1}/\U\1\L\2/g' <<< $s InFoRmAtIoN 

  • \L - Turn the replacement to lowercase until a \U or \E is found

  • \U - Turn the replacement to uppercase until a \L or \E is found


gawk (GNU awk) approach:

awk -v FPAT="[a-z]" '{ s=""; for(i=1;i<=NF;i++) { s=s""((i%2)? toupper($i) : $i)} print s }' <<< $s InFoRmAtIoN 
  • FPAT="[a-z]" - pattern representing field value

Another awk variation using split() function:

awk '{ n=split($0,a,""); s=""; for(i=1;i<=n;i++) { s=s""((i%2)? toupper(a[i]): tolower(a[i])) } print s }' <<< $s InFoRmAtIoN 
  • split() returns the number of elements created
3
  • Actually there is a problem at the one witch starts with uppercase, last 2 characters are lowercase. InFoRmAtIoN not InFoRmAtIon Commented Jun 2, 2017 at 16:56
  • @antiks, check my update Commented Jun 2, 2017 at 17:18
  • Note that split(string, array, "") is also a GNU extension, though now widely supported even if not POSIX. Commented Jun 2, 2017 at 21:48
1

POSIXly

awk ' { for(i = 1; i <= length; i++) { c = substr($0, i, 1) printf "%s", (i%2 ? toupper(c) : tolower(c)) } print "" }' < words.txt 
0
perl -pe ' ($_ = lc) =~ s/([a-z])([^a-z]*)(.)/\L$1$2\U$3/g; $_ .= y/a-zA-Z/A-Za-z/r; ' 
  1. Convert the input line to all lowercase.
  2. Change the case alternately to lower then upper of the chars on either side of non-alphabet. It could be nothing also, meaning the alphas are consecutive.
  3. Finally, reverse the case using the y, aka, tr command to get both versions.

Usage

s="InformatioN"; echo "$s" | perl -pe '....'

results:

iNfOrMaTiOn InFoRmAtIoN 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.