Home > Software engineering >  and how can i surround each word within a string with double qoutes in bash
and how can i surround each word within a string with double qoutes in bash

Time:04-30

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"

CodePudding user response:

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"

CodePudding user response:

Using sed

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