2013-07-08 24 views
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 

這些工作都沒有。我應該怎麼做?

+0

它的工作原理只是刪除第二個到最後一個字符? – ckersch

+0

我很好,只需刪除倒數第二個字符。 –

+0

我相信你有使用'bash'的理由,但是真的覺得使用支持'JSON'的語言會更容易和更乾淨。只需將文件行讀入數組,將數組序列化爲'JSON',並將其保存迴文件。 –

回答

1

的問題是,當你寫:

sed ... file > file 

bash解釋th e > 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相同)。

1

,而不是生成錯誤的語法Javascript數組,然後試圖修復它,我會建議生成正確的語法使用JavaScript awk腳本是這樣的:

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 
+0

哇,我真的需要學習awk。這太混亂了! –

+0

相信我,一旦你閱讀了一點awk,它就不會讓人感到困惑或畏縮。 – anubhava

+0

@glennjackman:非常感謝,讓它可讀。現在看起來好多了。 – anubhava

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 
1

改變你的腳本寫這個:

[ 
    'chicago' 
    ,'indianapolis' 
    ,'denver' 
    ,'miami' 
    ] 
相關問題