[英]Bash: Split up loop based on number of enumerations to process several files
[英]BASH - Split file into several files based on conditions
我有一個具有以下結構的文件( input.txt
):
>day_1
ABC
DEF
GHI
>day_2
JKL
MNO
PQR
>day_3
STU
VWX
YZA
>month_1
BCD
EFG
HIJ
>month_2
KLM
NOP
QRS
...
我想將此文件拆分為多個文件( day.txt
; month.txt
; ...)。 每個新的文本文件將包含所有“標題”行(以>
開頭的行)及其內容(兩個標題行之間的行)。
因此, day.txt
為:
>day_1
ABC
DEF
GHI
>day_2
JKL
MNO
PQR
>day_3
STU
VWX
YZA
和month.txt
:
>month_1
BCD
EFG
HIJ
>month_2
KLM
NOP
QRS
在這種情況下,我不能使用split -l
,因為每個類別(天,月等)的行數都不相同。 但是,每個子類別具有相同的行數(= 3)。
編輯:根據OP現在添加1更多解決方案。
awk -F'[>_]' '/^>/{file=$2".txt"} {print > file}' Input_file
說明:
awk -F'[>_]' ' ##Creating field separator as > or _ in current lines.
/^>/{ file=$2".txt" } ##Searching a line which starts with > if yes then creating a variable named file whose value is 2nd field".txt"
{ print > file } ##Printing current line to variable file(which will create file name of variable file's value).
' Input_file ##Mentioning Input_file name here.
跟隨awk
可能會幫助您。
awk '/^>day/{file="day.txt"} /^>month/{file="month.txt"} {print > file}' Input_file
您可以將記錄分隔符設置為>
,然后僅根據$1
給出的類別設置文件名。
$ awk -v RS=">" 'NF {f=$1; sub(/_.*$/, ".txt", f); printf ">%s", $0 > f}' input.txt
$ cat day.txt
>day_1
ABC
DEF
GHI
>day_2
JKL
MNO
PQR
>day_3
STU
VWX
YZA
$ cat month.txt
>month_1
BCD
EFG
HIJ
>month_2
KLM
NOP
QRS
由於每個子類別由相同數量的行組成,因此可以使用grep
的-A
/ --after
標志來指定在標頭后匹配的行數。
因此,如果您事先知道類別列表,則只需grep其子類別的標題即可將它們及其內容重定向到正確的文件:
lines_by_subcategory=3 # number of lines *after* a subcategory's header
for category in "month" "day"; do
grep ">$category" -A $lines_by_subcategory input.txt >> "$category.txt"
done
您可以在這里嘗試 。
請注意,這不是最有效的解決方案,因為它必須為每個類別瀏覽一次輸入。 相反,其他解決方案可以瀏覽內容,並通過一次將每個子類別重定向到各自的文件。
這是>name_number
格式的通用解決方案
$ awk 'match($0, /^>[^_]+_/){k = substr($0, RSTART+1, RLENGTH-2);
if(!(k in a)){close(op); a[k]; op=k".txt"}}
{print > op}' ip.txt
>name_
,則match($0, /^>[^_]+_/)
k = substr($0, RSTART+1, RLENGTH-2)
保存name
部分 if(!(k in a))
如果在數組中找不到鍵 a[k]
將鍵添加到數組 op=k".txt"
輸出文件名 close(op)
print > op
輸入記錄打印到保存在op
文件名
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.