LoginSignup
0
1

More than 5 years have passed since last update.

bash > sedで使う s/20161102/20161121/g といった文字列の右側の日付をbashスクリプトの実行時引数で変更する > v0.1..v0.2

Last updated at Posted at 2017-01-17
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 とその-devel
mpich.x86_64 3.1-5.el6とその-devel
gcc version 4.4.7 (とgfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.1を使用。
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

sedで使うことになるs/20161102/20161121/gのような文字列の右側の日付(20161121)をbash scriptの引数で指定して変更できるようにした。
(そうでないと単調作業を繰り返すことになり、失敗する)。

v0.1

bash script

replace_dates_170117_exec
#!/usr/bin/env bash

if [ $# -lt 2 ]; then
    echo "ERROR: too few arguments"
    echo ""
    echo "  [cmd] [current date] [previous date]"
    echo "  e.g. cmd 20161020 20161019"
    exit
fi

fmt1='s/20161102/20161121/g'
fmt2='s/20161101/20161120/g'

fmt1=$(echo $fmt1 | sed 's/20161121/'$1'/g')
echo $fmt1
fmt2=$(echo $fmt2 | sed 's/20161120/'$2'/g')
echo $fmt2

引数なし実行例

$ bash replace_dates_170117_exec 
ERROR: too few arguments

  [cmd] [current date] [previous date]
  e.g. cmd 20161020 20161019

引数指定実行例

$ bash replace_dates_170117_exec 20161020 20161119
s/20161102/20161020/g
s/20161101/20161119/g

fmt1, fmt2という変数になっているので、あとは以下のような使い方をする。

sed $fmt1 $oldfile | sed $fmt2 > $newfile

v0.2

以下の方が実はシンプルだった。

replace_dates_170117_exec
#!/usr/bin/env bash

if [ $# -lt 2 ]; then
    echo "ERROR: too few arguments"
    echo ""
    echo "  [cmd] [current date] [previous date]"
    echo "  e.g. cmd 20161020 20161019"
    exit
fi

fmt1='s/20161102/'$1'/g'
fmt2='s/20161101/'$2'/g'

echo $fmt1
echo $fmt2

備考

current dateからprevious date自動計算を実装する方法があるが、面倒そうなのでしていない。

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