やりたいこと
jsonファイルをcsvにして使用している。
csvにしたデータをawkでいじろうとしたとき、区切り文字以外にデータの中身にカンマがあり、うまく処理できない。
jsonファイルの中にあるカンマを削除する
テストファイル
test.json
[
{
"id": "1",
"text": "text1 , test1"
},
{
"id": "2",
"text": "text2 , test2"
}
[
jqのgsub→失敗
tostringで配列が崩れて、@csvができなくなってしまう。
# cat test.json | jq '.[]|tostring|gsub(",";"comma")'
"{\"id\": \"1\"comma\"text\": \"text1 comma test1\"}"
"{\"id\": \"2\"comma\"text\": \"text2 comma test2\"}"
結局sedに頼る
分かりやすさのため、下記の例ではカンマ除去は削除ではなく、commaに変更している
カンマ除去の確認
# cat test.json | sed s/[^\"|^\}],/comma/g
[
{
"id": "1",
"text": "text1 comma test1"
},
{
"id": "2",
"text": "text2 comma test2"
}
[
CSV変換
# cat test.json | sed s/[^\"|^\}],/comma/g| jq -r '.[]|[.id, .text]|@csv'
"id": "1","text": "text1 comma test1"
"id": "2","text": "text2 comma test2"