Remi.b Remi.b - 4 months ago 18
Bash Question

Paste single strings with an array in Bash

What would be a bash equivalent of the following R function?

vec=4:9
out=paste0("foo_",vec,"_bar")
out

"foo_4_bar" "foo_5_bar" "foo_6_bar" "foo_7_bar" "foo_8_bar" "foo_9_bar"

Answer

You can use declare an array with suffix and prefix and then use brace expansion to populate incrementing numbers:

arr=("foo_" "_bar") # array with suffix and prefix
echo "${arr[0]}"{4..9}"${arr[1]}" # brace expansion

foo_4_bar foo_5_bar foo_6_bar foo_7_bar foo_8_bar foo_9_bar
Comments