一个读取文件内容的shell脚本

如下展示的是一个shell脚本,该脚本可以2行2行的读取文件中的内容,然后把读取到的文件内容保存到一个名为target.json的文件当中,然后打印出target.json中的内容,打印完毕删除target.json文件,然后再新建target.json文件,然后再读入两行内容,然后再打印,再删除,直到源文件被读完。贴到博客的目的是做个笔记,毕竟本人没有专门学个shell编程,这些脚本中的某些语法可能后续会用到,所以算是做了个储备。

#!/bin/bash

count=0
rm target.json
touch target.json


while read line;do

((count++))

{
        echo $line >> target.json

        if [ $count -ge 2 ] && [ $((count%2)) -eq 0 ];then
                sudo cat target.json
                echo "2 line is reached!, current count is:"$count
                count=0
                sudo rm -f target.json
                touch target.json
        fi

}
      
done < $1
echo 'last submit'
    

假设保存该脚本的文件名是readLine.sh。则用法是: ./readLine.sh + 目标文件名。 该脚本改编自如下脚本,原文链接是: 原始脚本来源,原脚本顺便也张贴出来:

#!/bin/bash

count=0
rm target.json
touch target.json


while read line;do

((count++))

{
        echo $line >> target.json

        if [ $count -gt 100000 ] && [ $((count%2)) -eq 0 ];then
                count=0
                curl -XPOST localhost:9200/_bulk --data-binary @target.json > /dev/null
                rm target.json
                touch target.json
        fi

}

done < $1
echo 'last submit'
curl -XPOST localhost:9200/_bulk --data-binary @target.json > /dev/null