Bash脚本将文件的每一行保存到一系列文件中?

时间:2017-03-22 13:39:15

标签: bash

我有一个文件在文件的每一行都有一个json字符串

我想将该文件的每一行保存到一个单独的json文件中,并可选择在每行保存到文件之前运行命令。

我该怎么做?

1 个答案:

答案 0 :(得分:-1)

以下将执行此操作

save_each_line_of_file_to_a_file.sh /tmp/dump.json

save_each_line_of_file_to_a_file.sh

#!/usr/bin/env bash

function show_help()
{
  IT="
usage: FILE {OUTPUT_PREFIX} {OUTPUT_POSTFIX} ${OUTPUT_FOLDER}

e.g. 

/tmp/myfile           -> generates files in pwd, 1,2,3,4, etc for each line
/tmp/myfile OUT json  -> generates files in pwd, OUT1.json,OUT2.json,OUT3.json,OUT4.json, etc for each line
"

  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

OUTPUT_PREFIX=${2:-}
OUTPUT_POSTFIX=${3:-}
OUTPUT_FOLDER=${4:-}
EXTRA_CMD=${5:-}

FILE=${1:-/dev/stdin}

INDEX=1
while read line
do
  OUTPUT_FILENAME="${OUTPUT_FOLDER}${OUTPUT_PREFIX}$INDEX${OUTPUT_POSTFIX}"
  echo $OUTPUT_FILENAME
  INDEX=$((INDEX+1))

if [ -z "$EXTRA_CMD" ]
then
  echo $line > $OUTPUT_FILENAME
else
  echo $line | $EXTRA_CMD > $OUTPUT_FILENAME
fi
done < "$FILE"


      echo "$IT"
      exit
    }

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

OUTPUT_PREFIX=${2:-}
OUTPUT_POSTFIX=${3:-}
OUTPUT_FOLDER=${4:-}
EXTRA_CMD=${5:-}

FILE=${1:-/dev/stdin}

INDEX=1
while read line
do
  OUTPUT_FILENAME="${OUTPUT_FOLDER}${OUTPUT_PREFIX}$INDEX${OUTPUT_POSTFIX}"
  echo $OUTPUT_FILENAME
  INDEX=$((INDEX+1))

if [ -z "$EXTRA_CMD" ]
then
  echo $line > $OUTPUT_FILENAME
else
  echo $line | $EXTRA_CMD > $OUTPUT_FILENAME
fi
done < "$FILE"