0

我的输入文件如下:

B0000001201012345519680415EN
B0000001201052323219921114
B0000001701233333319510802LN
B0000001701238999919460920
B0000000247974444419611219TN
B0000000246666666619910804
B0000000247777777719940329

我想根据开始的 9 个字节(B00000012)将第一条记录“EN”复制到第二条记录。预期的输出是:

B0000001201012345519680415EN
B0000001201052323219921114EN
B0000001701233333319510802LN
B0000001701238999919460920LN
B0000000247974444419611219TN
B0000000246666666619910804TN
B0000000247777777719940329TN

我需要用 unix shell 脚本编写这个

4

3 回答 3

1

这将适用于您的输入:

awk '!(x = substr($0,27)) { print $0 r; next } { r = x }1' file

但是,如果需要检查前九个字符,它将失败。要执行此检查,请尝试以下操作:

awk 'x = substr($0,27) { a[substr($0,0,9)]=x } (y = substr($0,0,9)) in a && !x { print $0 a[y]; next }1' file

结果:

B0000001201012345519680415EN
B0000001201052323219921114EN
B0000001701233333319510802LN
B0000001701238999919460920LN
B0000000247974444419611219TN
B0000000246666666619910804TN
B0000000247777777719940329TN
于 2012-12-29T01:10:02.967 回答
1

使用 Perl:

perl -lape '$m = $1 if /([A-Z][A-Z])$/; s/(?<=[0-9]) *$/$m/' input

输出:

B0000001201012345519680415EN
B0000001201052323219921114EN
B0000001701233333319510802LN
B0000001701238999919460920LN
B0000000247974444419611219TN
B0000000246666666619910804TN
B0000000247777777719940329TN
于 2012-12-28T22:38:08.250 回答
1

如果您考虑使用 awk,这是一个经典的FIELDWIDTHS用法示例:

awk -vFIELDWIDTHS="9 17 2" -vOFS="" '{if($1 in a)$3=a[$1];else a[$1]=$3}1' file
于 2012-12-29T00:46:26.993 回答