Reputation: 178
I am new in bash and need help in this problem.
#!/bin/bash
str="This Is My Bash String"
mod="-val"
# Loop through characters of str. If index is 0, insert mod at position 0. And if the current index contains space (" "), then insert mod after the space.
echo -e str
# This should output: -valThis -valIs -valMy -valBash -valString
How can I achieve this?
Upvotes: 0
Views: 99
Reputation: 2778
build_command_line() {
local -ar tokens=(${@:2})
printf '%s\n' "${tokens[*]/#/"$1"}"
}
Now let’s test it a bit:
mod='-val'
str='This Is My Bash String'
build_command_line "$mod" "$str"
build_command_line "$mod" $str
build_command_line "$mod" "$str" Extra Tokens
build_command_line "$mod" $str 'Extra Tokens'
To “modify” str
, as you specify, just reassign it:
str="$(build_command_line "$mod" "$str")"
printf '%s\n' "$str"
Upvotes: 1
Reputation: 19545
Alternative to parameter expansion:
#!/usr/bin/env bash
str="This Is My Bash String"
mod="-val"
# Split string words into an array
IFS=' ' read -ra splitstr <<<"$str"
# Print each element of array, prefixed by $mod
printf -- "$mod%s " "${splitstr[@]}"
printf \\n
Upvotes: 1
Reputation: 88553
With bash and Parameter Expansion:
echo "$mod${str// / $mod}"
Output:
-valThis -valIs -valMy -valBash -valString
Upvotes: 7