如何替换最后一次出现的逗号

时间:2013-07-08 19:16:38

标签: javascript bash sed

我正在编写一个带有此文件的bash脚本:

Chicago
Indianapolis
Denver
Miami

并将其变为:

[
    'chicago',
    'indianapolis',
    'denver',
    'miami',
]

问题是这是一个JavaScript数组,我需要删除最后一行的最后一个逗号。我试着跟踪最后一行并用sed替换它:

lastline=1

echo [ > cities_array.txt

while IFS=$'\n' read -r line || [[ -n "$line" ]]; do
    city=$(echo $line | sed -e 's/\([A-Z]\)/\l\1/')

    echo '    '$city',' >> cities_array.txt

    let lastline++
done < cities.txt

echo ] >> cities_array.txt

sed -e "$lastline"'s/,//' cities_array.txt > cities_array.txt

最后一行绝对没有写入文件,删除所有内容。我也尝试过:

sed -e '"$lastline"s/,//' cities_array.txt > cities_array.txt
sed -e '$lastlines/,//' cities_array.txt > cities_array.txt

这些都不起作用。我该怎么做?

4 个答案:

答案 0 :(得分:1)

而不是生成错误的语法Javascript数组然后尝试修复它我建议使用像这样的awk脚本生成正确的语法Javascript:

awk 'NF>0{a[cnt++]=$1} END{print "["; for(i=0; i<length(a)-1; i++)       
      printf("\t\"%s\",\n", a[i]); printf("\t\"%s\"\n];\n", a[i])}' file

有额外的空格:

awk '
    NF>0 { a[cnt++] = $1 } 
    END {
        print "["
        for(i=0; i<length(a)-1; i++)       
            printf("\t\"%s\",\n", a[i])
        printf("\t\"%s\"\n];\n", a[i])
    }
' file

答案 1 :(得分:1)

问题是当你写:

sed ... file > file

bash在> file开始之前解释sed并清空文件。

您可以使用

sed -i ... file

进行“就地”编辑


顺便说一句,你可以让整件事变得更简单:

{
  echo -n '['
  while read -r line && [[ -n "$line" ]]; do echo "'${line,,}'"; done | paste -sd,
  echo ']'
} < cities.txt > cities_array.txt

虽然这样会产生一条长线而不是每条线一个城市(尽管javascript也是如此。)

答案 2 :(得分:1)

更改脚本以改为编写:

 [
   'chicago'
   ,'indianapolis'
   ,'denver'
   ,'miami'
  ]

答案 3 :(得分:0)

sed '
# on line 1 insert the opening bracket
1i\
[
# on each line, replace the first char with whitespace, a quote and the lowercase char
s/./    "\l&/
# on each line, close the quote and append a comma
s/$/",/
# on the last line, remove the trailing comma
$s/,$//
# on the last line, append the closing bracket
$a\
]
' file
[
    "chicago",
    "indianapolis",
    "denver",
    "miami"
]

更紧凑

sed -e '1i [' -e 's/./    "\l&/; s/$/",/; $s/,$//; $a ]' file