Using awk or sed command how can i encrypt the characters for a particular column.For every character it should replace the third charter of alphabets.Example replace "A" with "C" and "B" with "D"..like this it should replace for all characters in particular column.
Using below command i am able to replace the values in particular column.but not sure to replace like explain above.
awk -F, -v OFS=',' '$3="xxxxx" substr($3,6)' file
Hello katakamvivek,
Following code may help you in same. Let's say we have an example file named file_1.
cat file_1
R.Singh test abcdefgh
awk '{split("abcdefghijklmnopqrstuvwxyz", A,"");while(j++<=26){if(j==25 || j==26){D[A[j]]=A[j];} else {D[A[j]]=A[j+2]}};while(i++<=length($3)){S=S D[substr($3,i,1)]};$3=S;print}' file_1
Output will be as follows.
R.Singh test cdefghij
EDIT: Adding a non one-liner form for solution now.
cat file_1.ksh
awk '{
split("abcdefghijklmnopqrstuvwxyz", A,"");
while(j++<=26){
if(j==25 || j==26)
{
D[A[j]]=A[j]
}
else
{
D[A[j]]=A[j+2]
}
};
while(i++<=length($3)){
S=S D[substr($3,i,1)]
};
$3=S;
print
}' file_1
EDIT2: Here I want to mention fact that I have put logic here in code so when letter y or z comes in column 3rd then those letters will be remained as it is, if you need them too changed to, you can try it with a minor change in if
section, where I am setting array D's value.
EDIT3: Previous solution was having only small letters logic, adding small and block letters in solution now.
awk '{
split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", A,"");
while(j++<=52){
if(j==25 || j==26 || j==51 || j==52)
{
D[A[j]]=A[j]
}
else
{
D[A[j]]=A[j+2]
}
};
while(i++<=length($3)){
S=S D[substr($3,i,1)]
};
$3=S;
print
}' file_1
Example for above code:
#####Input_file:
cat file_1
R.Singh test abcdefghABCETRFG
######After running above EDIT#3 code in script as follows.
./file_1.ksh
R.Singh test cdefghijCDEGVTHI
Thanks,
R. Singh
Comments on the the previous solution:
The split() and the following loop are static; it is more efficient to place them in the BEGIN section.
And in the main section it is better to initialize a loop variable (use a for loop!), in case there is more than one line.
The split( , , "")
is not understood by all awk versions, others might need
lenA=split("a b c d e f g ...", A)
--
Here is a solution with a string
cat file
abc1,abc2,abc3,abc4
cat crypt3.sh
awk -F, -v OFS=, '
BEGIN {
chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
lchars=length(chars)
}
function crypt(s) {
s1=""
for (pos=1; pos<=length(s); pos++) {
c=substr(s,pos,1)
i=index(chars,c)
c1=substr(chars,1+(1+i)%lchars,1)
s1=s1 (i>0 ? c1 : c)
}
return s1
}
{
$3=crypt($3)
print
}
' "$@"
sh crypt3.sh file
abc1,abc2,cde3,abc4
Perl version:
perl -aF, -ne '$F[2]=~tr/a-zA-Z/c-zA-Zab/; print join(",",@F)' file
1 Like