'and how can i surround each word within a string with double qoutes in bash

This didnt work as it didnt pout a space in and only put one quote in on the end of the words sed -r "s/ /\"/g" didnt work.

input a string like "word1 word2 hello world" I expect the following output: "word1" "word2" "hello" "world"



Solution 1:[1]

You can use

sed 's/[^[:space:]]*/"&"/g' file > newfile
sed -E 's/[^[:space:]]+/"&"/g' file > newfile

In the first POSIX BRE pattern, [^[:space:]]* matches zero or more chars other than whitespace chars and "&" replaces the match with itself enclosed with double quotes. In the first POSIX ERE pattern, [^[:space:]]+ matches one or more chars other than whitespace.

See the online demo:

#!/bin/bash
s="word1 word2 hello world"
sed -E 's/[^[:space:]]+/"&"/g' <<< "$s"
# => "word1" "word2" "hello" "world"
sed 's/[^[:space:]]*/"&"/g' <<< "$s"
# => "word1" "word2" "hello" "world"

Solution 2:[2]

A pure bash solution using printf that doesn't require any regex or external tool:

s="word1 word2 hello world"
set -f
printf -v r '"%s" ' $s
set +f

echo "$r"
"word1" "word2" "hello" "world"

PS: Use echo "${r% }" is you want to remove trailing space.

Solution 3:[3]

Using sed

$ echo "word1 word2 hello world" | sed 's/\S\+/"&"/g'
"word1" "word2" "hello" "world"

Solution 4:[4]

Given this string stored in a variable named instr:

$ instr='word1 word2 hello world'

You could do:

$ read -r -a array <<< "$instr"
$ printf -v outstr '"%s" ' "${array[@]}"
$ echo "${outstr% }"
"word1" "word2" "hello" "world"

or if you prefer:

$ echo "$instr" | awk -v OFS='" "' '{$1=$1; print "\"" $0 "\""}'
"word1" "word2" "hello" "world"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew
Solution 2
Solution 3 HatLess
Solution 4 Ed Morton