シェル芸160本ノック解答例 その4

技術評論社から出版された『1日1問、半年以内に習得 シェル・ワンライナー160本ノック』の解答例です。


問題31

$ sed -E 's/(<strong>)([^<]+)/\1\U\2/g' iampen.txt
This is <strong>A PEN</strong>. I am a pen.
<pre>Are you pen?</pre> <strong>YES</strong>, I am.

# `perl`を使った別解
$ perl -nlE 's{<(strong)>(.+?)</\1>}{<$1>\U$2\E</$1>}g;say' iampen.txt
This is <strong>A PEN</strong>. I am a pen.
<pre>Are you pen?</pre> <strong>YES</strong>, I am.

問題32

$ perl -C -lnE 'say if $_ eq reverse' kaibun.txt
たけやぶやけた
らくまのまくら
くまをまく
わたしまけましたわ
まさかさかさま

問題33

$ for f in {,not_}kaibun; do [ "$(grep -o . "$f")" = "$(grep -o . "$f" | tac)" ] && echo "$f は回文" || echo "$f は回文ではない"; done
kaibun は回文
not_kaibun は回文ではない

問題34

$ perl -C -aE '$_=$F[1];s/(\p{Han}+)(.*)/$1($F[0])$2/;s/(.+?)\)\1$/)$1/;say' furigana.txt
山田(やまだ)
頑張(がんば)る
爆発(ばくはつ)する
激(はげ)しい

問題35

$ perl -C -lnE 's/(\p{katakana}{4})\p{katakana}.*/\1/;say length." $_"' speech.txt
25 21世紀に入ってからのIT業界を中心としたパラダイ
4 ジャスト
45 個人間であらゆるアセットをシェアするビジネスが注目を浴びており、共有経済、いわゆるシェアリ
22 顧客体験の高品質化、満足度、いわゆるサティス

問題36

# Perlでは、`() = $str =~ m/PATTERN/g`で指定文字列の出現回数を取得できます
# なお、この解答例にある`()=/\(/g``() = $_ =~ m/\(/g`を簡略化したものです
$ sed 's/)(/)\n(/g' message.txt | perl -C -lnE 'say if (()=/\(/g) == (()=/\)/g)' | tr -d '()\n' | xargs
いんしゅ

問題37

$ perl -C -0777 -lnE 's/\n//g;say $1 while /((.+?)\2)/g' diarydiary.txt
私は私は
シェル芸シェル芸
問題問題
すす
いろいろ

問題38

$ t=$(cat this_is_it.txt); while [[ "$t" =~ '&' ]]; do t=$(echo "$t" | sed 's/$/<br>/g' | w3m -T text/html -dump -cols 999); done; echo "$t"
$ x='() { :;}; echo vulnerable' bash -c "echo this is a test"
vulnerable
this is a test

問題39

$ fold -sw31 bash_description.txt | sed 's/ $//'
Bash is an sh-compatible
command language interpreter
that executes commands read
from the standard input or
from a file. Bash also
incorporates useful features
from the Korn and C shells
(ksh and csh).

問題40

$ sed -Ez 's/\n(、|。)/\1\n/g' kanjinum.txt | sed -E 's/[〇一二三四五六七八九十百千万億兆]+/"$(echo & | numconv)"/g;s/^/echo /;s/^echo +$//' | sh
私が小学1年生の時は、
47都道府県の位置
と名前を全て覚えるくらいに
物覚えは良かったですが、
テストで100点満点を
取り、親から5000000000000000円を
プレゼントされることは
ありませんでした。
Written on October 19, 2022