Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefix to each word of each line in bash

Tags:

grep

bash

sed

I have a variable called deps:

deps='word1 word2'

I want to add a prefix to each word of the variable.

I tried with:

echo $deps | while read word do \ echo "prefix-$word" \ done

but i get:

bash: syntax error near unexpected token `done'

any help? thanks

like image 691
Christopher Loen Avatar asked Jul 08 '16 09:07

Christopher Loen


1 Answers

For well behaved strings, the best answer is:

printf "prefix-%s\n" $deps

as suggested by 123 in the comments to fedorqui's answer.

Explanation:

  • Without quoting, bash will split the contents of $deps according to $IFS (which defaults to " \n\t") before calling printf
  • printf evaluates the pattern for each of the provided arguments and writes the output to stdout.
  • printf is a shell built-in (at least for bash) and does not fork another process, so this is faster than sed-based solutions.
like image 168
Heinrich Hartmann Avatar answered Oct 11 '22 14:10

Heinrich Hartmann