Replace the characters in every line of a file, if it match a condition - Unix -


i have file "dummy" in which: if 15 character of file matches "r" , 28 character of file matches "d" 53-56 characters should replaced 0.

i have tried using below script, it's not working.

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

input file: dummy

05196220141228r201412241308d201412200055sa1155we130800031300sl07y051 05196220141228r201412241308a201412220350sa0731su1950lax c00020202020 05196220141228r201412241308d201412200055sa1155we130823455300sl07y051 05196220141228n201412241308a201412240007tu0548we1107mel c00000000015 07054820141228n201412220850d201412180300th1400mo085000040300ul180001 

output should be:

05196220141228r201412241308d201412200055sa1155we130800001300sl07y051 05196220141228r201412241308a201412220350sa0731su1950lax c00020202020 05196220141228r201412241308d201412200055sa1155we130800005300sl07y051 05196220141228n201412241308a201412240007tu0548we1107mel c00000000015 07054820141228n201412220850d201412180300th1400mo085000040300ul180001 

there no need loop through file bash loop. sed alone can handle it:

$ sed -r '/^.{14}r.{12}d/s/(.{52}).{4}/\10000/' file 05196220141228r201412241308d201412200055sa1155we130800001300sl07y051 05196220141228r201412241308a201412220350sa0731su1950lax c00020202020 05196220141228r201412241308d201412200055sa1155we130800005300sl07y051 05196220141228n201412241308a201412240007tu0548we1107mel c00000000015 07054820141228n201412220850d201412180300th1400mo085000040300ul180001 

this uses expression sed '/pattern/s/x/y/' file: in lines matching pattern, replace x y.

in case,

  • /^.{14}r.{12}d/ line starts 14 characters followed r, 12 characters followed d.
  • (.{52}).{4} 52 characters followed 4 characters , replace them with...
  • \10000 first block followed 0000.

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

php - Bypass Geo Redirect for specific directories -

php - .htaccess mod_rewrite for dynamic url which has domain names -