LoginSignup
17
16

More than 5 years have passed since last update.

python ワンライナーに挑戦 〜 初心者のお勉強 m(_ _)m

Last updated at Posted at 2017-12-03

bc,tac,grep,sed,awk を python ワンライナーにしてみました。
python に慣れる目的で、日常的に使えたらいいと思ったのがモチベーションです。
しかし、実際に使っているのは「電卓(簡単な計算)」だけです…:sweat:

以下、"file1.txt" は任意のテキストファイルです。

1) 電卓(簡単な計算)

● bc

$ echo "scale=4; 1.23 * 4.56" | bc
5.6088
$ echo "2^3" | bc
8

● python

$ python -c "print(1.23 * 4.56)"
5.6088
$ python -c "print(2**3)"
8

2) テキストをそのまま出力 (以降のサンプルの準備)

● cat

$ cat file1.txt

● python ※ これならcatだけでいいのでは…

$ cat file1.txt | python -c 'import sys; [print(l,end="") for l in sys.stdin]'

3) テキストファイルを逆順(末尾→1行目)の順に出力

● tac

$ tac file1.txt

● python

$ cat file1.txt | python -c 'import sys; [print(l,end="") for l in reversed(list(sys.stdin))]'

4) 指定行の抜き出し (例: 2〜5行目)

● sed

$ sed -n 2,5p file1.txt

● python

$ cat file1.txt | python -c 'import sys, re; [print(l,end="") for l in list(sys.stdin)[1:5]]'

※ [1:4] ではなく [1:5] であることに注意。何故?

5) 指定カラムの抜き出し (例: 2カラム目を抜き出し)

● awk

$ awk '{print $2}' file1.txt

● python

$ cat file1.txt | python -c 'import sys, re; [(lambda x: print(x[1]) if len(x) > 1 else print(""))(i) for i in [l.split() for l in sys.stdin]]'

6) 文字列検索 (例: "ABC"を検索)

● grep

$ grep -e "ABC" file1.txt
$ grep -i -e "ABC" file1.txt

● python

$ cat file1.txt | python -c 'import sys, re; [print(l,end="") for l in sys.stdin if re.search("ABC",l)]'
$ cat file1.txt | python -c 'import sys, re; [print(l,end="") for l in sys.stdin if re.search("ABC",l,re.IGNORECASE)]'

7) 文字列置換 (例: "ABC"を"XYZ"に置換)

● sed

$ sed -e 's/ABC/XYZ/' file1.txt
$ sed -e 's/ABC/XYZ/g' file1.txt
$ sed -e 's/ABC/XYZ/ig' file1.txt

● python

$ cat file1.txt | python -c 'import sys,re; [print(re.sub("ABC","XYZ",l,1),end="") for l in sys.stdin]'
$ cat file1.txt | python -c 'import sys,re; [print(re.sub("ABC","XYZ",l),end="") for l in sys.stdin]'
$ cat file1.txt | python -c 'import sys,re; [print(re.sub("ABC","XYZ",l,0,re.IGNORECASE),end="") for l in sys.stdin]'

いいわけ(まとめ)

電卓以外のワンライナーを実際に使うことは無さそう:sob:ですが、リスト処理、内包表記、lambda式の練習になったので記事にしてみました:sweat_smile:

17
16
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
17
16