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
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\Uor\Eis found\U- Turn the replacement to uppercase until a\Lor\Eis 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
- Actually there is a problem at the one witch starts with uppercase, last 2 characters are lowercase. InFoRmAtIoN not InFoRmAtIonantiks– antiks2017-06-02 16:56:24 +00:00Commented Jun 2, 2017 at 16:56
- @antiks, check my updateRomanPerekhrest– RomanPerekhrest2017-06-02 17:18:30 +00:00Commented Jun 2, 2017 at 17:18
- Note that
split(string, array, "")is also a GNU extension, though now widely supported even if not POSIX.Stéphane Chazelas– Stéphane Chazelas2017-06-02 21:48:53 +00:00Commented Jun 2, 2017 at 21:48
POSIXly
awk ' { for(i = 1; i <= length; i++) { c = substr($0, i, 1) printf "%s", (i%2 ? toupper(c) : tolower(c)) } print "" }' < words.txt perl -pe ' ($_ = lc) =~ s/([a-z])([^a-z]*)(.)/\L$1$2\U$3/g; $_ .= y/a-zA-Z/A-Za-z/r; ' - Convert the input line to all lowercase.
- 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.
- Finally, reverse the case using the
y, aka,trcommand to get both versions.
Usage
s="InformatioN"; echo "$s" | perl -pe '....'
results:
iNfOrMaTiOn InFoRmAtIoN