如果文件符合条件,则替换文件每一行中的字符 - Unix

时间:2015-06-04 10:38:08

标签: unix replace sed match conditional-statements

我有一个文件“虚拟”,其中: 如果文件的15个字符与“R”匹配,则文件的28个字符与“D”匹配 那么53-56个字符应该替换为0。

我已尝试使用以下脚本,但它无效。

for i in `cat dummy`
do
    if [[ `echo $i | cut -c15` = "R" ]] && [[ `echo $i | cut -c28` = "D" ]]
then
   sed -e 's/./0/53' -e 's/./0/54' -e 's/./0/55' -e 's/./0/56'
fi
done

输入文件:虚拟

05196220141228R201412241308D201412200055SA1155WE130800031300SL07Y051
05196220141228R201412241308A201412220350SA0731SU1950LAX C00020202020
05196220141228R201412241308D201412200055SA1155WE130823455300SL07Y051
05196220141228N201412241308A201412240007TU0548WE1107MEL C00000000015
07054820141228N201412220850D201412180300TH1400MO085000040300UL180001

输出应为:

05196220141228R201412241308D201412200055SA1155WE130800001300SL07Y051
05196220141228R201412241308A201412220350SA0731SU1950LAX C00020202020
05196220141228R201412241308D201412200055SA1155WE130800005300SL07Y051
05196220141228N201412241308A201412240007TU0548WE1107MEL C00000000015
07054820141228N201412220850D201412180300TH1400MO085000040300UL180001

1 个答案:

答案 0 :(得分:3)

无需使用bash循环遍历文件。仅sed就可以处理它:

$ sed -r '/^.{14}R.{12}D/s/(.{52}).{4}/\10000/' file
05196220141228R201412241308D201412200055SA1155WE130800001300SL07Y051
05196220141228R201412241308A201412220350SA0731SU1950LAX C00020202020
05196220141228R201412241308D201412200055SA1155WE130800005300SL07Y051
05196220141228N201412241308A201412240007TU0548WE1107MEL C00000000015
07054820141228N201412220850D201412180300TH1400MO085000040300UL180001

这使用表达式sed '/pattern/s/X/Y/' file:在与pattern匹配的行中,将X替换为Y

在这种情况下,

  • /^.{14}R.{12}D/行以任意14个字符开头,后跟R,然后是任意12个字符,后跟D
  • (.{52}).{4}查找任意52个字符,后跟任意4个字符,并将其替换为...
  • \10000第一个块后跟0000