文字列をシェルで、指定文字数に分割して結合するには
選択肢になるコマンドは、分割・結合でそれぞれ次の通り
- 分割
- flod
- grep
- 結合
- paste
- tr
などが使えることがわかった。
分割の例
fold -w2 grep -E -o '.{2}'
文字列を指定文字に分割する。fold コマンド
fold コマンドが便利。ruby であればsplit/grep などで出来る。
takuya@~$ echo $(openssl rand -hex 6) | fold -w1 0 3 3 9 5 2 f 0 7 3 1 e
fold -w コマンドは、指定バイトで切り出す。
takuya@Desktop$ echo $(openssl rand -hex 4) | fold -w4 d0ac 01f3
指定バイトなので日本語のようなユニコード文字列は3バイトで切り出す。
takuya@~$ echo ああああ | fold -w 3 あ あ あ あ
grep でもなんとか出来る
echo $(openssl rand -hex 4) | /bin/grep -i -E -o '.{2}' 7f 1c 10 ec
おお。grep 万能説!
さて、分割した文字列を結合するには
join かと思いきや、paste
を使うと便利だった。
paste -sd ':'
paste で複数行を結合
takuya@Desktop$ cat - | paste -sd "," a b c a,b,c
使いみち
xdd/hexdump/od 何かと組み合わせると便利かも
たとえば、画像のdumpをちょっと見る。
takuya@Desktop$ xxd -p -l 100 logo.png | ~/.bin/grep -i -E -o '.{2}' | paste -sd "," 89,50,4e,47,0d,0a,1a,0a,00,00,00,0d,49,48,44,52,00,00,00,60,00,00,00,2d,08,03,00,00,00,66,80,9e,b8,00,00,00,19,74,45,58,74,53,6f,66,74,77,61,72,65,00,41,64,6f,62,65,20,49,6d,61,67,65,52,65,61,64,79,71,c9,65,3c,00,00,03,12,69,54,58,74,58,4d,4c,3a,63,6f,6d,2e,61,64,6f,62,65,2e,78,6d,70,00,00,00,00,00
例えば、MACアドレスっぽいものを作る
takuya@~$ echo $(openssl rand -hex 6) | fold -w2 | paste -sd ':' 7e:25:cb:0b:70:ef
参考資料
http://stackoverflow.com/questions/7578930/bash-split-string-into-character-array