NodeX4
NodeX4

Reputation: 49

Wrap each word in string with characters using bash

Goal

I am attempting to create a function that takes a string as an argument and wraps each individual word within the string with double quotes and returns that as a string.

Attempted

What I tried is the below sed snippet, but it outputted the whole string wrapped in double quotes instead of each individual word. sed -r "s/ /\"/g"

Expect

function wordWrapper {
  # Do some magic here
}

var = wordWrapper "Hello World"
echo $var

should output "Hello" "World"

Upvotes: 1

Views: 1001

Answers (4)

anubhava
anubhava

Reputation: 785856

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.

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 204446

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"

Upvotes: 1

sseLtaH
sseLtaH

Reputation: 11247

Using sed

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

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627335

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"

Upvotes: 1

Related Questions