The problem is that when I execute this command
#!/bin/bash
for i in "${@:2}";
do
uniqueletters=$(echo $i | awk -v RS= '{$1=$1}1' | sed 's/ //g')
done
echo $uniqueletters
On this
7216859340 FRENCH ARABIC CHINESE
I only get CHINESE and both of these commands don't seem to execute
awk -v RS= '{$1=$1}1' | sed 's/ //g'
But my desired output is this please
FRENCHARABICCHINESE
CodePudding user response:
Putting awk
(or sed
) inside a shell loop is inefficient and considered an anti-pattern in most cases. You can accomplish what you're trying to do in a much simpler and more efficient way without using a loop and an external command:
#!/bin/bash
printf -v uniqueletters '%s' "${@:2}"
echo "$uniqueletters"
This uses printf
's implicit loop and the -v
option, which causes the output to be assigned to the variable uniqueletters
rather than being printed to the standard output.
Note: the variable name uniqueletters
doesn't make sense to me.
CodePudding user response:
Seems like you are always overwriting the value of the variable uniqueletters in the loop. What this means is that, uniqueletters will only contain the last letter after coming out of the loop.
The following is a simple fix for your code
#!/bin/bash
uniqueletters=""
for i in "${@:2}"; do
uniqueletters =$(echo $i | awk -v RS= '{$1=$1}1')
done
echo $uniqueletters