SuperNoob
SuperNoob

Reputation: 178

Modify bash string

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

Answers (5)

Andrej Podzimek
Andrej Podzimek

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

Léa Gris
Léa Gris

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

biwiki
biwiki

Reputation: 72

This might also do the job:

echo $mod$str |sed -e "s/ / $mod/g"

Upvotes: 1

Cyrus
Cyrus

Reputation: 88553

With bash and Parameter Expansion:

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

Output:

-valThis -valIs -valMy -valBash -valString

Upvotes: 7

user2683246
user2683246

Reputation: 3568

for word in $str
do echo -n " $mod$word"
done

Upvotes: 2

Related Questions