我随身携带以下文件:-
====== 20160606:034441 ====== Mango(Test)
TestName MangoT
Row 0
Season N
Name Safeda
Location Delhi
====== 20160606:034441 ====== Mango(Result)
TestName MangoR
Result 0
No_of_Mango 13
Quantity 2
Quantity 3
Quantity 6
Quantity 0
Quantity 1
Quantity 9
Quantity 54
Quantity 2
Quantity 4
Quantity 6
Quantity 76
Quantity 0
Quantity 99
Price 50
Price 70
Price 40
Price 30
Price 40
Price 30
Price 20
Price 60
Price 70
Price 80
Price 90
Price 30
Price 30
====== 20160606:034441 ====== Mango(Test)
TestName MangoT
Row 0
Season N
Name Alphonso
Location Mumbai
====== 20160606:034441 ====== Mango(Result)
TestName MangoR
Result 0
No_of_Mango 13
Quantity 5
Quantity 3
Quantity 1
Quantity 0
Quantity 7
Quantity 8
Quantity 70
Quantity 3
Quantity 23
Quantity 43
Quantity 734
Quantity 2
Quantity 929
Price 50
Price 70
Price 40
Price 30
Price 40
Price 30
Price 20
Price 60
Price 70
Price 80
Price 90
Price 30
Price 30
现在我需要上面文件中的两个基于 Mango 名称的输入文件,例如:- 文件名:-safeda.txt
TestName MangoR
Result 0
No_of_Mango 13
Quantity 2
Quantity 3
Quantity 6
Quantity 0
Quantity 1
Quantity 9
Quantity 54
Quantity 2
Quantity 4
Quantity 6
Quantity 76
Quantity 0
Quantity 99
Price 50
Price 70
Price 40
Price 30
Price 40
Price 30
Price 20
Price 60
Price 70
Price 80
Price 90
Price 30
Price 30
第二个文件名:-Alphonso.txt
TestName MangoR
Result 0
No_of_Mango 13
Quantity 5
Quantity 3
Quantity 1
Quantity 0
Quantity 7
Quantity 8
Quantity 70
Quantity 3
Quantity 23
Quantity 43
Quantity 734
Quantity 2
Quantity 929
Price 50
Price 70
Price 40
Price 30
Price 40
Price 30
Price 20
Price 60
Price 70
Price 80
Price 90
Price 30
Price 30
我需要使用 shell 脚本创建这两个文件。
答案1
这是一种方法:
$ awk '(/=====/){a=0}
(/\(Result\)\s*$/){a=1; next}
($1=="Name"){n=$2}
(a==1){print >> n".txt"}' file
解释
(/=====/){a=0}
:如果当前行匹配======
,则设置a
为0
。(/\(Result\)\s*$/){a=1; next}: if the current line ends with
(结果)followed by 0 or more whitespace, set
ato
1`并跳到下一行。($1=="Name"){n=$2}
:如果第一个字段是Name
,则将n
变量设置为第二个字段的值。(a==1){print >> n".txt"
:如果a
是,则将此行打印到名为(名称)且扩展名为1
的文件中。n
.txt
答案2
#!/bin/bash
filename=""
do_write=0
while read line
do
case $line in
==*Result*) do_write=1
;;
==*Test*) do_write=0
filename=""
;;
Name*) [[ $do_write == 0 ]] && filename=${line#Name }.txt
;;
"") # Skip blank lines
;;
*) [[ $do_write == 1 ]] && echo "$line" >> $filename
esac
done
使用您的输入文件:
$ head -10 input
====== 20160606:034441 ====== Mango(Test)
TestName MangoT
Row 0
Season N
Name Safeda
Location Delhi
====== 20160606:034441 ====== Mango(Result)
TestName MangoR
Result 0
我们得到结果:
$ ./parse < input
$ ls
Alphonso.txt input parse Safeda.txt
$ head Alphonso.txt
TestName MangoR
Result 0
No_of_Mango 13
Quantity 5
Quantity 3
Quantity 1
Quantity 0
Quantity 7
Quantity 8
Quantity 70
$ head Safeda.txt
TestName MangoR
Result 0
No_of_Mango 13
Quantity 2
Quantity 3
Quantity 6
Quantity 0
Quantity 1
Quantity 9
Quantity 54