本文介绍了如何在由定界符分隔的值周围添加双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采用一个字符串,其值用,分隔.我需要在双引号周围放置双引号",并在每次拆分后进行修整.

I take a string with values separated by ,. I need to place "around them" the double quotes and, after each split, do a trim.

这是我的实际代码:

input="TAG1, TAG2"
output='[ "'${input//, /\", \"}'" ]'
echo "$output"

可以正确显示:

[ "TAG1", "TAG2" ]

但是:

  1. 如果我使用input="TAG1,TAG2"(即,后没有空格),则不起作用
  2. 如果我使用input=" TAG1, TAG2 ",它将保留空格并且不会修剪每个匹配项.应该针对每个项目.
  1. It doesn't works if I use input="TAG1,TAG2" (i.e. no space after ,)
  2. If I useinput=" TAG1, TAG2 ", it keep spaces and don't trim each match. It should, for each item.

你会怎么做?

推荐答案

这是jq解决方案:

jq -cR '. | gsub("^ +| +$"; "") | split(" *, *"; "")' <<< "TAG1,TAG2"
["TAG1","TAG2"]

jq -cR '. | gsub("^ +| +$"; "") | split(" *, *"; "")' <<< "TAG1, TAG2"
["TAG1","TAG2"]

jq -cR '. | gsub("^ +| +$"; "") | split(" *, *"; "")' <<< "   TAG1,       TAG2     "
["TAG1","TAG2"]

PS::如果要输出漂亮的json,请删除-c.

PS: Remove -c if you want pretty json output.

您也可以使用awk:

cat comma.csv
BEGIN {
   FS = " *, *"
   OFS=", "
}
{
   for (i=1; i<=NF; i++) {
      gsub(/^ *| *$/, "", $i)
      $i = "\"" $i "\""
   }

   print "[ " $0 " ]"
}

并将其用作:

awk -f comma.csv <<< "TAG1, TAG2"
[ "TAG1", "TAG2" ]

awk -f comma.csv <<< "TAG1,TAG2"
[ "TAG1", "TAG2" ]

awk -f comma.csv <<< "   TAG1,   TAG2   "
[ "TAG1", "TAG2" ]


sed解决方案:


sed solution:

sed 's/^ */[ "/; s/ *$/" ]/; s/ *, */", "/g' <<< "       TAG1,        TAG2     "
[ "TAG1", "TAG2" ]    

sed 's/^ */[ "/; s/ *$/" ]/; s/ *, */", "/g' <<< "TAG1,TAG2"
[ "TAG1", "TAG2" ]

sed 's/^ */[ "/; s/ *$/" ]/; s/ *, */", "/g' <<< "TAG1 , TAG2"
[ "TAG1", "TAG2" ]

这篇关于如何在由定界符分隔的值周围添加双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 01:47