3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

bashで出力にダブルクォートをつける

Posted at

TL; DR

行ごとのやつ

$ echo -e "aaa bbb\nccc ddd" | jq -R .
"aaa bbb"
"ccc ddd"

列ごとのやつ

$ echo -e 'aaa bbb\nccc ddd' | sed 's/[^ ]\+/"&"/g'
"aaa" "bbb"
"ccc" "ddd"

動機

 bashで出力にダブルクォートを含める必要があるとき、エスケープを嫌ってシングルクォートを使いたくなる。

$ echo '"Hello, world"'
"Hello, world"
$ echo "\"Hello, world\""
"Hello, world"

 しかし変数を埋め込もうとするとシングルクォートは使えない。
 そこで上のようなちょっとした解決策が役に立つ。jqはjsonをシェルで扱うためのコマンドだ。sedのようにプリインストールされていないが、インストールしておいて損はない。

$ greeting=Bonjour target=monde
$ echo "$greeting, $target" | jq -R .
"Bonjour, monde"

 例えば、次のようにして標準出力をjsonのリストに押し込める。便利だ。

$ echo -e "Hello, world\nBonjour, monde" | jq -R . | jq -sc .
["Hello, world","Bonjour, monde"]
$ echo -e "Hello, world\nBonjour, monde" | jq -R . | jq -sc '{greetings: .}'
{"greetings":["Hello, world","Bonjour, monde"]}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?