例如,我有一个包含以下几行的文本文件。
输入
DD0TRANSID000019021210504250003379433005533665506656000008587201902070168304000.0AK 0000L00000.00 N 01683016832019021220190212N0000.001683065570067.000000.00000.0000000000000NAcknowledgment
DD0TRANSID000019021210504250003379433005535567606656000008587201902085381804000.0FC 0000L00000.00 N 53818538182019021220190212N0000.053818065570067.000000.00000.0000000000000NFirst Contact
DD0TRANSID000019021210510360003379433005535568006656000008587201902085381804000.0SR 0000L00000.00 N 53818538182019021220190212N0000.0
CC0TRANSID000019021210510360003379433005535568006656000008587201902085381804000.0SR 0000L00000.00 N 53818538182019021220190212N0000.0
我的要求是如果该行以“D”开头,则将从第 14 个位置到第 27 个位置的字符串替换为 D00000X(X 是一个带有左侧填充的数字)
如果我在第 14 个位置和第 27 个位置之间遇到与之前在文件中遇到的相同的字符串值,我应该替换为 D00000X,否则替换为 D00000X+1
输出
DD0TRANSID00001902121D000006003379433005533665506656000008587201902070168304000.0AK 0000L00000.00 N 01683016832019021220190212N0000.001683065570067.000000.00000.0000000000000NAcknowledgment
DD0TRANSID00001902121D000006003379433005535567606656000008587201902085381804000.0FC 0000L00000.00 N 53818538182019021220190212N0000.053818065570067.000000.00000.0000000000000NFirst Contact
DD0TRANSID00001902121D000007003379433005535568006656000008587201902085381804000.0SR 0000L00000.00 N 53818538182019021220190212N0000.0
CC0TRANSID000019021210510360003379433005535568006656000008587201902085381804000.0SR 0000L00000.00 N 53818538182019021220190212N0000.0
答案1
假设这些是日期/时间戳并按顺序递增
a=($(grep -Po "(?<=^D.{13}).{13}" testfile | uniq))
for ((i=0; i<${#a[@]}; i+=1)); do
s=${a[$i]}
sed -E -i "s/(D.{13})$s/\1${s:0:7}D$(printf '%06d' $((i+1)))/g" testfile
done
如果标记在文件中进一步重复,它将获得新的计数器增量。如果您不希望这样,则uniq
需要sort | uniq
将相同的计数器应用于整个文件中的相同标记。
顺便说一句,看起来您在示例中删除了位置 28 处的 0 。