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?

0

5 Answers 5

7

With bash and Parameter Expansion:

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

Output:

-valThis -valIs -valMy -valBash -valString
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

This is not the recommended way to split a string. See: stackoverflow.com/a/918931/7939871 IFS=' ' read -ra words <<< "$str"; for word in "${words[@]}"; do
1

This might also do the job:

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

Comments

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

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.