Search code examples
stringbashshellbash4

Deleting repeated characters in a string bash script


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?


Solution

  • 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