我的输入文件如下:
B0000001201012345519680415EN
B0000001201052323219921114
B0000001701233333319510802LN
B0000001701238999919460920
B0000000247974444419611219TN
B0000000246666666619910804
B0000000247777777719940329
我想基于起始9个字节(B00000012
)将第一个记录'EN'复制到第二个记录。
预期的输出是:
B0000001201012345519680415EN
B0000001201052323219921114EN
B0000001701233333319510802LN
B0000001701238999919460920LN
B0000000247974444419611219TN
B0000000246666666619910804TN
B0000000247777777719940329TN
我需要在unix shell脚本中编写这个
答案 0 :(得分:1)
使用Perl:
perl -lape '$m = $1 if /([A-Z][A-Z])$/; s/(?<=[0-9]) *$/$m/' input
输出:
B0000001201012345519680415EN
B0000001201052323219921114EN
B0000001701233333319510802LN
B0000001701238999919460920LN
B0000000247974444419611219TN
B0000000246666666619910804TN
B0000000247777777719940329TN
答案 1 :(得分:1)
如果您考虑使用awk,这是一个经典的 FIELDWIDTHS 用法示例:
awk -vFIELDWIDTHS="9 17 2" -vOFS="" '{if($1 in a)$3=a[$1];else a[$1]=$3}1' file
答案 2 :(得分: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