2

我正在编写一个接受此文件的 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

4 回答 4

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
于 2013-07-08T19:29:57.723 回答
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 相同。)

于 2013-07-08T19:30:54.150 回答
1

改变你的脚本来写这个:

 [
   'chicago'
   ,'indianapolis'
   ,'denver'
   ,'miami'
  ]
于 2013-07-08T23:45:06.257 回答
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
于 2013-07-08T19:51:48.440 回答