LoginSignup
1
3

More than 5 years have passed since last update.

bash > 任意の列数を持つファイルから3ステップずつ項目を抽出する実装 / $@: 全ての引数項目を渡す / set, Brace Expansionを使う

Last updated at Posted at 2017-03-04
動作環境
GeForce GTX 1070 (8GB)
ASRock Z170M Pro4S [Intel Z170chipset]
Ubuntu 14.04 LTS desktop amd64
TensorFlow v0.11
cuDNN v5.1 for Linux
CUDA v8.0
Python 2.7.6
IPython 5.1.0 -- An enhanced Interactive Python.
gcc (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
GNU bash, version 4.3.8(1)-release (x86_64-pc-linux-gnu)

PNM > ppmファイル > 1行に出力されるRGB値はファイルによって異なるようだ > 1行70文字制限
で見つかったppmファイルのBlue成分読込みの失敗。

任意の列数を持つファイルから3ステップずつ項目を抽出する実装が必要だ。

bashで実装した。

read_with_step_exec_170304
#!/usr/bin/env bash

extract_column() {
    ((cnt=1))
    for aword in $@;do
        mdl=$((cnt % 3))
        if [ $mdl -eq 1 ];then
            echo $aword
        fi
        ((cnt++))
    done    
}

list=$(cat $1 | tr '\n' ' ')
#echo $list # for debug

clm=$(extract_column $list)
echo $clm
sample.dat
1 2 3 4
5 6 7
8 9 10 11
実行
$ bash read_with_step_exec_170304 sample.dat 
1 4 7 10

学習事項

補足

(追記 2017/03/10)

@hasegitさんの記事
bashで文字列分解する時、cutやawkもいいけど、setの方が早い
のset使用と@magicantさんのコメントのread使用も気になる。

教えていただいた事項

(追記 2017/03/11)

@hasegitさんのコメントにてsetとBrace Expansionを使った方法を紹介いただきました。Brace Expansionというのは使い慣れていませんが、便利そうです。
情報感謝です。

それを元に、自分でも試してみたのが以下のコードです。
(cutを新たに使っています)

test_read_170311_exec
#!/usr/bin/env bash

set $(cat $1 | tr '\n' ' ')
pos=$(eval echo {1..${#}..3} | tr ' ' ',') # e.g. 1,4,7
echo $@ | cut -d ' ' -f $pos
結果
$ bash test_read_170311_exec sample.dat 
1 4 7 10

補足: posの行をsetの上に持って行くと失敗します。

1
3
2

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
1
3