Reputation: 15
My .txt file looks like as below (please consider it is 1GB file):
hello,12,abcd,xyz
welcome,13,abcd,yul
hai,14,abcd,ghk
Now, I want encrypt 1st and 3rd column as like below
zzyyy,12,zzzz,xyz
asdsddd,13,zzzz,yul
asd,14,zzzz,ghk
I have encrypt key like below
export key=ETAOINSHRDLUBCFGJMQPVWZYXK
Now, I need to apply this key in perl script to encrypt 1st and 3rd column in my file:
export key=ETAOINSHRDLUBCFGJMQPVWZYXK
perl -F, -lane '$F[$_] =~ tr/a-z/A-Z/ =~ tr/A-Z/"$key"/ for (0, 2); print join(",", @F)' file.txt
So, when run above script, the key not applied and second tr command not working. So, could you please kindly help to what is wrong in the script.
I simply need apply like below in above Perl script
tr "a-z" "A-Z" | tr "A-Z" "$key"
Upvotes: 1
Views: 152
Reputation: 247042
I see this in the documentation for tr///
:
there is never any variable interpolation, so "$" and "@" are always treated as literals.
So attempting to pass the key through the environment won't work. But you can do this to insert the shell variable into the perl code:
perl -F, -lane '
sub encode { my $str = uc shift; $str =~ tr/A-Z/'"$key"'/r; }
# ..............................................^^....^^
$F[$_] = encode($F[$_]) for (0, 2);
print join(",", @F)
' file.txt
output:
HIUUF,12,ETAO,xyz
ZIUAFBI,13,ETAO,yul
HER,14,ETAO,ghk
Or, use eval
perl -F, -lane '
sub encode { my $str = uc shift; eval "\$str =~ tr/A-Z/$ENV{key}/r" }
$F[$_] = encode($F[$_]) for (0, 2);
print join(",", @F)
' file.txt
Upvotes: 3