Reputation: 1167
$ landscape=aws,azure
$ echo $landscape
expected o/p:
aws-landscape,azure-landscape
How I am doing it now..!?
$ landscape=aws,azure
$ GITLANDSCAPE=$(echo $Landscapes | sed 's/,/-landscape,/g' | sed 's/$/-landscape/g')
$ echo $GITLANDSCAPE
Is there a better way to do it?
Upvotes: 1
Views: 1326
Reputation: 1230
with sed, you can do as this:
echo $landscape | sed -E 's/,|$/-landscape&/g'
aws-landscape,azure-landscape
or, you can do with awk:
echo $landscape | awk -F, '{print $1"-landscape,"$2"-landscape"}'
aws-landscape,azure-landscape
Upvotes: 2
Reputation: 189357
Using a comma to delimit your strings is probably the main pain point here. The shell naturally supports space-separated tokens.
printf '%s-landscape\n' aws azure
If you want to do something a bit more complex, maybe a loop.
sep=''
for token in aws azure; do
printf '%s%s-landscape' "$sep" "$token"
sep=','
done
If you want to do something even more complex, perhaps put them in an array. (This is not Bourne/POSIX sh
compatible, but a common extension in Ksh, Bash, etc.)
a=(aws azure)
for token in "${a[@]}"; do ...
As an aside, in Bash, there is also brace expansion:
printf '%s\n' {aws,azure}-landscape
This is tortured, but produces what you are asking:
printf '%s' {aws,\,azure}-landscape
The first comma separates the phrases between the braces. To include a literal comma in one of the phrases, we backslash it.
Upvotes: 2
Reputation: 22225
If I understand you right, you have a variable holding a comma-separated list of words. You want to add a fixed string, -landscape
, to each of these words, keeping the comma as separator.
This is one way to do it, provided that none of the words contains white space:
words1=ab,cd,ef,gh
words2=$(printf %s $words1 | xargs --delimiter , -L 1 printf "%s-landscape " | fmt -1 | paste -d, -s)
echo $words2
This would print
ab-landscape,cd-landscape,ef-landscape,gh-landscape
How it works: The xargs tears apart the words1 string into individual words and invokes printf to add -landscape to each. The resulting output is still separated by spaces, not by comma. With fmt, these words are put in separate lines, one line for each word. The final paste joins these lines with a comma.
Upvotes: 0
Reputation: 51868
Replacing the comma is not a particularly good style.
You can do it like this:
landscape=aws,azure
echo $landscape | awk 'BEGIN{FS=",";OFS=",";suffix="-landscape"}{print $1suffix,$2suffix}'
Output:
aws-landscape,azure-landscape
In the BEGIN
block you set the following variables:
Upvotes: 4