1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

スクリプトの絶対パスを環境変数の参照に置き換える sed コマンド

Posted at

目新しさはありませんが、たまに使いたくなった時に忘れているのでメモを残します。

シェルスクリプトなどで絶対パス(それも結構長い)が多く含まれている場合に、それを環境変数の参照に置き換えたくなることがあります。

まず、環境変数は定義済みという前提です。
置き換えは以下2点を気をつければ sed で手軽にできます。

  • 置換パタンはダブルクォート(")で囲む
  • \x24 がドルマーク($)を示す

以下は例です。
***/home1/hoge/fuga/nagai/mohitotsu/***に以下2つのファイルがあります。

data.txt
2016 9 22
2017 9 22
2018 9 22
2019 9 22
2020 9 22
2021 9 22
2022 9 22
weekday1.py
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import sys

weekday_jp = ["","","","","","",""]

for l in sys.stdin:
	l = l.rstrip("\r\n")
	d = list(map(int,l.split()))
	print("{}/{}/{}({})".format(d[0],d[1],d[2],weekday_jp[datetime.datetime(d[0],d[1],d[2]).weekday()]))

これを実行するスクリプトrun0.shです。

run0.sh
cat /home1/hoge/fuga/nagai/mohitotsu/data.txt | python /home1/hoge/fuga/nagai/mohitotsu/weekday1.py

こんな風に実行されます。

$ ./run0.sh 
2016/9/22(木)
2017/9/22(金)
2018/9/22(土)
2019/9/22(日)
2020/9/22(火)
2021/9/22(水)
2022/9/22(木)

ここで、ファイルのあるパスをFILEPATHという環境変数に設定します。
その変数に置き換えたスクリプトrun1.shを作ります。
2行目の sed コマンドがこの記事の本題です

export FILEPATH=/home1/hoge/fuga/nagai/mohitotsu
sed -s "s:${FILEPATH}:\x24{FILEPATH}:g" run0.sh > run1.sh
chmod +x ./run1.sh 

run1.shの内容です。

run1.sh
cat ${FILEPATH}/data.txt | python ${FILEPATH}/weekday1.py

ちゃんと同じ実行結果が得られます。

$ ./run1.sh 
2016/9/22(木)
2017/9/22(金)
2018/9/22(土)
2019/9/22(日)
2020/9/22(火)
2021/9/22(水)
2022/9/22(木)
1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?