這沒有用,因為它沒有在單詞的末尾添加一個空格,并且只在單詞的末尾加上一個引號sed -r "s/ /\"/g" didnt work。
輸入一個字串,如"word1 word2 hello world"
我期望的以下輸出:"word1" "word2" "hello" "world"
uj5u.com熱心網友回復:
使用它的純 bash 解決方案printf不需要任何正則運算式或外部工具:
s="word1 word2 hello world"
set -f
printf -v r '"%s" ' $s
set f
echo "$r"
"word1" "word2" "hello" "world"
PS:使用echo "${r% }"的是你要洗掉尾隨空格。
uj5u.com熱心網友回復:
您可以使用
sed 's/[^[:space:]]*/"&"/g' file > newfile
sed -E 's/[^[:space:]] /"&"/g' file > newfile
在第一個 POSIX BRE 模式中,[^[:space:]]*匹配零個或多個除空白字符以外的字符,"&"并將匹配替換為用雙引號括起來的自身。在第一個 POSIX ERE 模式中,[^[:space:]] 匹配除空格之外的一個或多個字符。
查看在線演示:
#!/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"
uj5u.com熱心網友回復:
使用sed
$ echo "word1 word2 hello world" | sed 's/\S\ /"&"/g'
"word1" "word2" "hello" "world"
uj5u.com熱心網友回復:
鑒于此字串存盤在名為 的變數中instr:
$ instr='word1 word2 hello world'
你可以這樣做:
$ read -r -a array <<< "$instr"
$ printf -v outstr '"%s" ' "${array[@]}"
$ echo "${outstr% }"
"word1" "word2" "hello" "world"
或者,如果您愿意:
$ echo "$instr" | awk -v OFS='" "' '{$1=$1; print "\"" $0 "\""}'
"word1" "word2" "hello" "world"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/468639.html
上一篇:命令結束時如何結束回圈
