I have a line with string of characters (BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB)
I like to replace a specific character (for e.g, 4th character) to lower case.
I tried this awk command,
awk '{for (i=1; i<=NF; i) { $i=toupper(substr($i,1,1)) tolower(substr($i,2)); } print }' input > output
input file contains the string "BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB"
This awk command gives this output: "Bccdddcdccddddddabcdabcabdbacbdcaaccbbcabacbccabcacbcdcccbdbacdcbbcbcbcccacadaaccababadbcbaabbbccbb"
Now, how do I change all the other characters to lowercase except the 4th character?
Thank you
CodePudding user response:
On that line you can use something like this. Through -F ''
every letter is now a field which can be accessed with $i
.
$ cat line
BCCDDDCDCCDDDDDDABCDABCABDBACBDCAACCBBCABACBCCABCACBCDCCCBDBACDCBBCBCBCCCACADAACCABABADBCBAABBBCCBB
$ awk -F '' '{ for(i=1;i<=NF; i){
if(i!=4){
printf("%s",tolower($i))}
else{
printf("%s",$i)} } print "" }' line
bccDddcdccddddddabcdabcabdbacbdcaaccbbcabacbccabcacbcdcccbdbacdcbbcbcbcccacadaaccababadbcbaabbbccbb
CodePudding user response:
An example in python of a function that makes it, I let you understand the logic and adapt it to your problem.
def f(s):
# your result
res = ""
# iterate though each character in the string
for i in range(0, len(s)):
# on some condition, here 4th character, you add a lowercase character to your result
if(i == 3):
res = s[i].lower()
# on some other conditions an upper case character...
elif condition_2_to_create:
res = s[i].upper()
# or just the character as it is in the string without modification
else:
res = s[i]
# Then return your result
return res