1. 程式人生 > >一個讀取檔案內容的shell指令碼

一個讀取檔案內容的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