0

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?

SuperNoob
  • 170
  • 1
  • 10

5 Answers5

7

With bash and Parameter Expansion:

echo "$mod${str// / $mod}"

Output:

-valThis -valIs -valMy -valBash -valString
Cyrus
  • 84,225
  • 14
  • 89
  • 153
2
for word in $str
do echo -n " $mod$word"
done
user2683246
  • 3,399
  • 29
  • 31
  • This is not the recommended way to split a string. See: https://stackoverflow.com/a/918931/7939871 `IFS=' ' read -ra words <<< "$str"; for word in "${words[@]}"; do` … – Léa Gris Aug 21 '21 at 11:51
1

This might also do the job:

echo $mod$str |sed -e "s/ / $mod/g"
biwiki
  • 62
  • 3
1

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
1
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"
Andrej Podzimek
  • 2,409
  • 9
  • 12