2條shell命令搞定文件切割

linux裏的head和tail命令分別用來查看一個文件的頭幾行和尾幾行。例如:

head -n 100 test用來查看test文件裏頭100行的內容……

現在用head和tail進行文件切割,即把一條包含100行記錄的文件,切成n個平均長度的文件,例如:
./cutfile.sh test 4, 表示將test文件切爲n個文件,每個文件包含4行test的內容,如果test有100行,n即爲25.如果test有10行,則n爲3,3個文件分別包含,4,4,2行記錄。

這裏假設切割完的文件自動在原文件名後面加0,1,2……,例如:
test切割成3份文件,名稱分別爲:test0,test1和test2

下面來看看cutfile.sh具體怎麼實現:
#print arguments
echo "argument 1 is:"$1
echo "argument 2 is:"$2

#variable initialization
file_no=0
curr_len=$2
total_len=$(cat $1|wc -l)

echo "total length is:"$total_len

#cut lines in file
while [ "$curr_len" -le "$total_len" ]
do
  echo "current length is:"$curr_len
  head -n $curr_len $1|tail -n $2 > $1$file_no
  let file_no++
  curr_len=$(expr $curr_len + $2)  
done

#if total_len mod curr_len = 0
if [ $(expr $curr_len - $2) -eq $total_len ]
then
  exit
fi

#cut rest lines in file
if [ "$curr_len" -gt "$total_len" ]
then
  echo "cut rest file"
  head -n $curr_len $1|tail -n $(expr $2 - $curr_len + $total_len ) > $1$file_no
fi


基本思路(以./cutfile.sh test 4爲例,其中test的內容爲
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15):
第一次:head -n 4 test|tail -n 4 > test0
test0 內容爲:1 2 3 4

第二次:head -n 8 test|tail -n 4 > test1
test1 內容爲:5 6 7 8

第三次:head -n 12 test|tail -n 4 > test2
test2 內容爲:9 10 11 12

最後一次有可能剩餘的記錄數不滿4個,如果
head -n 16 test|tail -n 4 > test3

這樣test3的內容爲:12 13 14 15,而實際應該是13 14 15.

在這裏,我們對最後一次不完全切割單獨做,思路如下:
head -n 16 test|tail -n 4-16+15 > test3

其中4-16+15其實表示:參數2-當前疊加數(16)+test總長度,在代碼中的表示即爲:
$(expr $2 - $curr_len + $total_len ) 

於是test3的結果即爲:
13 14 15
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章