我有这样的输入,
[Data.11]
Store,100,,,,,,,,,,,,,,,,,,,5222
Store,101,,,,,,,,,,,,,,,,,,,5235
[Data.12]
TaxSchedulePt,5899,2,110.0100,99999999.99,,8.8750
TaxSchedulePt,5900,1,0,110.00,,0.0000
[Data.13]
TaxSchedulePt,5900,1,0,110.00,,0.0000
TaxSchedulePt,5900,2,110.0100,99999999.99,,8.8750
首先需要找到[Data.] 在给定的输入文件中找到,如果 [Data.在给定的输入文件中找到的 ] 需要将特定的 [Data.*] 值写入单独的文件中。
[Data.11] 的预期输出文件
Store,100,,,,,,,,,,,,,,,,,,,5222
Store,101,,,,,,,,,,,,,,,,,,,5235
[Data.12] 的预期输出文件
TaxSchedulePt,5899,2,110.0100,99999999.99,,8.8750
TaxSchedulePt,5900,1,0,110.00,,0.0000
[Data.13] 的预期输出文件
TaxSchedulePt,5900,1,0,110.00,,0.0000
TaxSchedulePt,5900,2,110.0100,99999999.99,,8.8750
这是我尝试过的,
filename=$1
Var1=Data.18
if grep -wq "$Var1" $filename ;
then
awk '$1 ~ /Data[.]18/' > /ttk/new/data.dcn
else
echo "not Worked"
fi
答案1
awk 'BEGIN{d=0;p=0} d==1&&/\[Data\.[0-9]+\]/{p=0} p==1{print} /\[Data\.[0-9]+\]/&&d==0{p=1;d=1}'
说明:在一天开始时,我们没有打印部分 (p=0),也没有找到数据部分 (d=0)。如果 p==1,我们正在打印,打印该行。如果遇到数据线并且我们还没有找到数据部分,则打开打印并记录我们已经找到数据部分。如果找到数据部分但我们已经找到数据部分,请关闭打印。
答案2
如果i want to print exactly [Data.18] valus only
正如你所说一条评论是您的正确要求(并更改18
为12
给定更新的示例输入)然后:
$ awk '{sub(/\r$/,"")} /^\[/{key=$1; next} key=="[Data.12]"' file
TaxSchedulePt,5899,2,110.0100,99999999.99,,8.8750
TaxSchedulePt,5900,1,0,110.00,,0.0000
或者如果If [Data.16] found write a separate file and if [Data.18] was found write a separate file
正如你所说另一条评论那么你的正确要求是:
$ awk '{sub(/\r$/,"")} /^\[/{close(out); out=$1; next} {print > out}' file
$ head *Data*
==> [Data.11] <==
Store,100,,,,,,,,,,,,,,,,,,,5222
Store,101,,,,,,,,,,,,,,,,,,,5235
==> [Data.12] <==
TaxSchedulePt,5899,2,110.0100,99999999.99,,8.8750
TaxSchedulePt,5900,1,0,110.00,,0.0000
==> [Data.13] <==
TaxSchedulePt,5900,1,0,110.00,,0.0000
TaxSchedulePt,5900,2,110.0100,99999999.99,,8.8750
以上是针对此输入文件运行的:
$ cat file
[Data.11]
Store,100,,,,,,,,,,,,,,,,,,,5222
Store,101,,,,,,,,,,,,,,,,,,,5235
[Data.12]
TaxSchedulePt,5899,2,110.0100,99999999.99,,8.8750
TaxSchedulePt,5900,1,0,110.00,,0.0000
[Data.13]
TaxSchedulePt,5900,1,0,110.00,,0.0000
TaxSchedulePt,5900,2,110.0100,99999999.99,,8.8750
ssub(/\r$/,"")
是删除带有 DOS 行结尾(OP 具有)的行末尾的 CR,尽管它会导致发生字段分割,因此对性能造成很小的影响,但我们正在使用$1
而不是$0
输入行尾随空白在键值或输出文件名中是不受欢迎的。