789757 ランダム
 HOME | DIARY | PROFILE 【フォローする】 【ログイン】

さすらいのプログラマ

CSVの行・列入替(シェル版)

kshのみでCSVの行・列を入れ替えるシェル
#!/usr/bin/ksh

# -------------------------------------------------------------------
# CSV rotate shell
# -------------------------------------------------------------------

# -- check argument
if [ $# -ne 2 ]; then
    echo "usage : $0 [source filename] [dest filename]"
    exit
fi

# -- check file
if [ -f $1 ]; then
    FILENAME=$1
else
    echo "$1 not found."
    exit
fi

DESTNAME=$2

# -- store IFS
OLDIFS="$IFS"

# -- get max column count
IFS="\n"
COLCOUNT=0
while read BUFFER
do
    IFS=","
    set $BUFFER
    if [ $# -gt $COLCOUNT ]; then
    COLCOUNT=$#
    fi
    IFS="\n"
done < ${FILENAME}

# -- temporary filename and item filename
TEMPFILE=./__TEMPFILE__
ITEMFILE=./__ITEMFILE__

# -- clear item file
cat /dev/null >$ITEMFILE

# -- main process
IFS="\n"
# -- initialize item counter
ITEMCTR=0
while read BUFFER
do
    # -- change IFS for row in CSV
    IFS=","
    # -- separate items
    set $BUFFER
    MAXCOL=$#
    # clear temporary file
    cat /dev/null >${TEMPFILE}
    # -- reset column counter
    COLCTR=0
    # -- set item
    TARGET=$1
    while [ $COLCTR -lt $COLCOUNT ]
    do
    # -- change IFS for item file
    IFS="\n"
    #
    if [ $ITEMCTR -gt 0 ]; then
      COMMA=","
    else
      COMMA=""
    fi
    # -- read item file
    read ITEMS
    # -- add new item
    ITEMS="${ITEMS}${COMMA}${TARGET}"
    # -- write to temporary file
    echo "$ITEMS" >>${TEMPFILE}
    # -- increment column counter
    COLCTR=`expr $COLCTR + 1`
    # -- next item (if exist ...)
    if [ $COLCTR -lt $MAXCOL ]; then
      shift
      TARGET=$1
    else
      TARGET=
    fi
    done < ${ITEMFILE}
    # -- increment item counter
    ITEMCTR=`expr $ITEMCTR + 1`
    # -- override item file
    cp ${TEMPFILE} ${ITEMFILE}
    IFS="\n"
done < ${FILENAME}

# -- reset IFS
IFS="$OLDIFS"

# -- copy from item file to dest file
cp ${ITEMFILE} ${DESTNAME}
# -- remove temporary file and item file
rm -f ${TEMPFILE}
rm -f ${ITEMFILE}


※転載禁止です。


Copyright (c) 1997-2019 Rakuten, Inc. All Rights Reserved.