0

I have this code to delete repeated characters in a string:

awk -v FS="" '{
    for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "AABBCC"

The result is:

ABC

Which is exactly what I want; but the problem is when I pass a variable it removes the repeated letters but it doesn't update the value of the variable. For example:

KEY=AABBCC
awk -v FS="" '{
    for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "$KEY"
echo the new key is: $KEY

The result is:

ABC

the new key is: AABBCC

How can I get the updated version of the KEY?

Community
  • 1
  • 1
Alladin
  • 1,010
  • 3
  • 27
  • 45
  • You just need to assign the result of the awk command to the variable again. `KEY=$(awk ...)` – Etan Reisner Aug 31 '14 at 13:28
  • @EtanReisner sorry i didn't notice that. it was a mistake when i rewrote the code. – Alladin Aug 31 '14 at 13:33
  • Which is what I responded to him in my previous comment. Clearly your original code was working. – Etan Reisner Aug 31 '14 at 13:33
  • @EtanReisner do you have an answer to this question? – Alladin Aug 31 '14 at 13:53
  • My answer is in that first comment of mine. And was repeated by both submitted answers below. I didn't feel the need to submit a real answer for this and was going to let someone else do that if they wanted to get credit for it. – Etan Reisner Aug 31 '14 at 14:01

2 Answers2

4

Try this:

KEY=AABBCC
KEY=$(awk -v FS="" '{ for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str) } END {print str}' <<< "$KEY")
echo $KEY

Output:

ABC
Cyrus
  • 84,225
  • 14
  • 89
  • 153
2

You need to assign the output of the awk command to the variable like so:

KEY=AABBCC
KEY=$(awk -v FS="" '{
    for(i=1;i<=NF;i++)str=(++a[$i]==1?str $i:str)
}
END {print str}' <<< "$KEY")
echo the new key is: $KEY

will result in the new key is: ABC

ShaneQful
  • 2,140
  • 1
  • 16
  • 22