標籤:
需求說明
在bash中,我們可以使用split命令輕鬆實現文本的拆分。現在增加兩點需求:
1. 在每份拆分檔案的頭部插入title,便於查看。
2. 拆分檔案的名稱為源檔案名稱前加編號,如1.source.txt。
總體思路
1. 執行split命令,把源檔案按指定行數拆分成若干小檔案。
2. 遍曆這些小檔案,並建立名稱符合要求的拆分檔案,然後插入title並拷貝檔案內容。
具體步驟
1. 首先執行如下命令,人工造出一個包含9999行的大檔案source.txt。
echo "" | awk ‘BEGIN{for (i = 0; i < 9999; i++) print(201503200001+i)".jpg"}‘ > source.txt
2. 假設指定行數為3000,執行如下命令,這個檔案將被拆成4個小檔案。
split -l 3000 source.txt
得到的4個小檔案名稱分別為xaa, xab, xac, xad。
3. 現在逐個建立名稱符合要求的小檔案,並往檔案中存內容,像下面這樣:
touch 1.source.txtecho "#photo_file_name">1.source.txt cat xaa>>1.source.txt
4. 最好能把冗餘的檔案刪除,因此在完成第3步後執行rm xaa命令。
5. 主體已經有了,現在需要把它們拼起來形成一個shell指令碼。
建立指令碼檔案split.sh並在vi中開啟:
touch split.shchmod +x split.sh
vi split.sh
編輯split.sh,輸入以下內容:
#!/bin/bash# 1. 參數檢查if [ $# -ne 2 ]; then echo -e "wrong parameter\nUsage: $0 filename linecount"; exit 1;fi# 2. 拆分檔案# 2.1 清掉可能的舊檔案rm -f x??rm -f *.$1# 2.2 執行拆分split -l $2 $1# 3. 遍曆小檔案xfiles=$(ls x??)index=1for current_file in $xfiles; do new_file=$index.$1 touch $new_file # 寫入title和內容 echo "#photo_file_name">$new_file cat $current_file>>$new_file # 刪除冗餘檔案 rm -f $current_file # 列印小檔案摘要 echo "~~~ $new_file"; head -3 $new_file echo "......" tail -2 $new_file echo "" # 檔案索引加1 index=$(($index+1))done
運行效果
[email protected]:~/demo $ ./split.sh source.txt 3000~~~ 1.source.txt#photo_file_name201503200001.jpg201503200002.jpg......201503202999.jpg201503203000.jpg~~~ 2.source.txt#photo_file_name201503203001.jpg201503203002.jpg......201503205999.jpg201503206000.jpg~~~ 3.source.txt#photo_file_name201503206001.jpg201503206002.jpg......201503208999.jpg201503209000.jpg~~~ 4.source.txt#photo_file_name201503209001.jpg201503209002.jpg......201503209998.jpg201503209999.jpg[email protected]:~/demo $ ls1.source.txt 2.source.txt 3.source.txt 4.source.txt source.txt split.sh
小提示
1. shell指令碼對空格敏感,賦值時不能留空格,比如xfiles = $(ls x??)就是錯誤的。
2. 變數的引用必須用$符號。
3. 當出現syntax error: unexpected end of file錯誤,請把注意力放在syntax error,大多數情況下是指令碼語法錯誤。(當然也不排除檔案格式的問題,可在vi中輸入:set fileformat查看檔案格式是否為unix。)
使用shell指令碼實現文本拆分