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

テキストファイルの固定長化(bashスクリプト)

Last updated at Posted at 2025-06-14

bash を 利用し, サンプルテキストファイルの固定長化(80桁/行)を行う

  • Mainframe の JCLサンプルコードを, 80桁(バイト)+改行 固定長テキストファイル化します。

オペレーティングシステム

Operating System: Ubuntu 22.04.5 LTS
          Kernel: Linux 6.8.0-60-generic
    Architecture: x86-64

bash バージョン

$ bash --version
GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)

80桁化 スクリプト

#!/bin/bash

# 1行の文字数(=バイト数)
LRECL=80
SMPL_D=../JCL_SAMPLE
TMP_F=$(/usr/bin/mktemp)


# -------------------------------------------------
# EXIT function
# -------------------------------------------------
function        __f_EXIT()
{
        (
        # 終了時にテンポラリファイルを削除します
        [[ -f $TMP_F ]] && rm -f $TMP_F
        ) 2>/dev/null
}

trap    __f_EXIT        EXIT


# -------------------------------------------------
# 指定桁数分のスペースを標準出力へ出力する
# 第一引数 : 桁数(バイト数)
# -------------------------------------------------
function        __f_add_sp()
{
        [[ -z "$1" ]] && return 1
        printf '%*s' "$1"
        return $?
}


# -------------------------------------------------
# (標準入力より)行を読込み、$LRECL よりも桁数が少ない場合,
# $LRECL に合うように, 空白を行末に補う
# -------------------------------------------------
function        __f_l_READ()
{
        local   L=
        local   RRC=0
        local   LS=0

        for (( RRC = 0 ; RRC == 0 ; ))
        do
                read -r L
                RRC=$?

                [[ $RRC -ne 0 ]] && continue
                [[ -z "$L"    ]] && continue

                # 桁数取得
                LS=${#L}

                # 桁数が $LRECL より小さい時,行末に 空白 を 補う
                [[ $LS -lt $LRECL ]] && L="$L$( __f_add_sp $(( ${LRECL} - ${LS})) )"

                # 改行コード無し
###             printf "${L}" >>$TMP_F
                # 改行コード付き
                echo "$L" >>$TMP_F
        done

        return 0
}


# --------------------------------------------------
# MAIN
# --------------------------------------------------

        #
        # LANG=C により, 変数の桁数[${#xx}]の結果が文字数(=バイト数)となる
        #
        LANG=C

        # サンプルの保存先ディレクトリへ移動
        cd $SMPL_D

        # サンプルテキストファイルの読み込み
        for I in $( ls *.txt )
        do
                # テンポラリファイルの初期化(/dev/nullで上書き)
                echo "$(</dev/null)" >$TMP_F

                __f_l_READ >$TMP_F <$I

                [[ -s $TMP_F ]] && cp $TMP_F $I
        done

exit 0
0
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
0
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?