LoginSignup
1
2

More than 5 years have passed since last update.

linux / sed / bash > ファイル名を変更 + 内容変更 > 同じルールで > bashスクリプト

Last updated at Posted at 2016-11-09
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
GNU sed version 4.2.1
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

やりたいこと

$ cat AA_201611 
20161101,3.141592
20161102,3.141592
20161103,3.141592
$ cat BB_201611 
20161101,2.718281
20161102,2.718281
20161103,2.718281

上記のようなファイルが30個程度ある。
201611は2016年11月を示す。
これらのファイルを2017年12月用に変更したい。

以下の変更をする

  • ファイル名の変更
    • 例: AA_201611をAA_201712に
  • ファイル内容の変更
    • 例: 201611を201712に

つまり、変更ルールは「ファイル名変更」「ファイル内容変更」ともに同じルール。

bashスクリプト

#!/usr/bin/env bash

fmt='s/201611/201712/g' ## change this

mkdir OLD

for oldfile in $(ls *_201611);do ## change this
#   echo $oldfile
    newfile=$(echo $oldfile | sed $fmt)
    echo $newfile
    sed $fmt $oldfile > $newfile
    mv $oldfile OLD/
done
実行
$ bash replace_exec 
AA_201712
BB_201712

以下のように変更できた。これでSublime Textで一括置換 x N回の作業はしなくていい。

$ cat AA_201712 
20171201,3.141592
20171202,3.141592
20171203,3.141592
$ cat BB_201712 
20171201,2.718281
20171202,2.718281
20171203,2.718281

注意点としては、置換の文字列が本当にユニークなものかどうか。
ファイル内容に無関係の数値があり、そこに201611などがあれば余計な置換をしてしまう。

v0.2 置換行数の表示

diffを使って置換した行数+アルファを表示するようにした。

#!/usr/bin/env bash

fmt='s/201611/201712/g' ## change this

mkdir OLD

for oldfile in $(ls *_201611);do ## change this
#   echo $oldfile
    newfile=$(echo $oldfile | sed $fmt)
    echo $newfile
    sed $fmt $oldfile > $newfile
    diff $oldfile $newfile | wc
    mv $oldfile OLD/
done
結果
$ bash replace_exec 
AA_201712
      8      14     132
BB_201712
      8      14     132

こうしておくと、余計な置換をしたファイルがあればすぐに見つかる。

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