それマグで!

知識はカップより、マグでゆっくり頂きます。 takuya_1stのブログ

習慣に早くから配慮した者は、 おそらく人生の実りも大きい。

シェルコマンド、sed で改行の置換して、一行にする。

sed で改行の置換をする方法

 sed ':a;N;$!ba;s/\n/<replacement_txt>/g' 

いろいろフラグを追加したら出来るみたい。

記号にギョっとするけど、ちゃんと出来るよ

takuya@aqua-iot$ cat -  | sed ':a;N;$!ba;s/\n/ /g'
Hello
world
I
am
Hello world I  am

一瞬記号に面食らって何だこれ?ってなると思うんだけど、ちゃんと出来るよ

これは次のsedオプションを置換指定に入れたGNU sed 記法です

なので、ぎょっとする記号は、次のオプションと同じですね。

sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' file

実行サンプル

実際にヤってみた。

takuya@atom:/var/www/epgrec$ curl -s 'http://hatenablog.com/oembed?url=http%3A%2F%2Ftakuya-1st.hatenablog.jp%2Fentry%2F20120229%2F1330519953&format=xml' |  sed ':a;N;$!ba;s/\n/<text>/g'
<?xml version="1.0" encoding="utf-8" standalone="yes"?><text><oembed><text>  <author_name>takuya_1st</author_name><text>  <author_url>http://blog.hatena.ne.jp/takuya_1st/</author_url><text>  <blog_title>それマグで!</blog_title><text>  <blog_url>http://takuya-1st.hatenablog.jp/</blog_url><text>  <categories><text>  </categories><text>  <description>XMLをもらったけど、階層ツリーがむちゃくちゃでわからない tidy -utf8 -i --input-xml true --indent-cdata true ./sample.xml しかも昔にエントリ書いてるし。www tidy のインストール。 mac はじめから linux debian gnu/linuxは aptで windows コンパイル済みバイナリをどこかでダウンロードしてくる cygwin setup.exeや apt-cyg で XMLの整形 tidyでxmlを整形するには・ -xml オプションを付ける。tidy -xml ./sample.xml または tidy-…</description><text>  <height>190</height><text>  <html>&lt;iframe src=&quot;http://takuya-1st.hatenablog.jp/embed/20120229/1330519953&quot; title=&quot;XMLを整形(tidy)して読みやすく、貼りつけやすくする。 - それマグで!&quot; class=&quot;embed-card embed-blogcard&quot; scrolling=&quot;no&quot; frameborder=&quot;0&quot; style=&quot;display: block; width: 100%; height: 190px; max-width: 500px; margin: 10px 0px;&quot;&gt;&lt;/iframe&gt;</html><text>  <image_url></image_url><text>  <provider_name>Hatena Blog</provider_name><text>  <provider_url>http://hatenablog.com</provider_url><text>  <published>2012-02-29 21:52:33</published><text>  <title>XMLを整形(tidy)して読みやすく、貼りつけやすくする。</title><text>  <type>rich</type><text>  <url>http://takuya-1st.hatenablog.jp/entry/20120229/1330519953</url><text>  <version>1.0</version><text>  <width>100%</width><text></oembed>

参考資料

http://www.canbike.org/information-technology/sed-delete-carriage-returns-and-linefeeds-crlf.html

https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed

2018/03/05

追記した

2019/05/16

カテゴリ整理