I have strings coming in from the user that are of the form... 1,2,3 with any amount of numbers. What I want to do is replace the numbers with the corresponding values at the indeces of each of these numbers from an array. So say my array has [tom][jerry][sue]. I'd want my string to look like tom,jerry,sue when I'm doing processing it. Should I be using grep? bash?
1 Answer
string="1,2,3"
names=( nobody tom jerry sue )
indexes=( $(sed 's/,/ /g' <<< "$string") )
result=""
pad=""
for i in ${indexes[@]}
do
result="$result$pad${names[$i]}"
pad=","
done
echo "$result"
Explanation:
- Simulate input string from user
- Array of names, indexed from 0 (nobody) to 3 (sue)
- Array of numbers generated from string by requesting
sedto replace commas by blanks. There are other ways to do that, but I tend to usesedstill. For example,indexes=( ${string//,/ }will do the job without invokingsedor any external program. - The output goes in
result. - I use
padto build up strings with a separator. - Loop over the numbers in the array
indexes - Result is the concatenation of what was there before, the padding, and the name represented by the number in
$i. - Set the pad to a comma for the second and subsequent iterations.
- Echo the result.
I didn't count the 'do' or 'done' lines.
I should've been more specific and asked you how the
sedsyntax works.
There are 4 interesting parts to the line:
indexes=( $(sed 's/,/ /g' <<< "$string") )
indexes=( ... )This is an array assignment. It will take the words produce by whatever is in
...and treat them as the elements of the array. That's how thenames=( ... )assignment works, of course.sed ... <<< "$string"This runs the
sedcommand with the value of"$string"as its standard input. This is abashextension called a Here String. Thus the only line of input is "1,2,3".'s/,/ /g'is asedcommand that substitutes a space for every comma in the input. Thus, the output is a line containing1 2 3.$( ... )runs the command contained within the parentheses (thesedcommand) and treats the output as a string.
The overall effect is the same as:
indexes=( 1 2 3 )
The spaces around the parentheses aren't strictly necessary, but I think they make the array assignment easier to spot — but it is a notation I'm still 'learning' (having to remember to use).
3 Comments
sed here: indexes=( $(sed 's/,/ /g' <<< "$string") ) can be replaced with IFS=, read -a indexes <<< "$string".