Try this: perl -i.bak -pe "s/\'/\t/;" somefile.dat

The entire problem can be solved with a one-liner. Using tr or y instead of s might be good in this case because s loses performance due to regex computation. You don't really need a regex here -- you're only replacing one character -- unless, of course, you only want to replace the first one, in which case use s.

Modifying a file, then putting the modified file in place of the original file, is known as modifying the file "in place", which is done using the i switch. The .bak is to make a backup as somefile.dat.bak, so that in case of error, you can recover the original data. Since you are modifying it in place, your while(<FILE>) { ... } loop becomes a while(<>) { ... } loop. To get the modified data to be output back to the file, you need to use a print statement, thus: while(<>) { ... print; } This can be accomplished by using the p switch, which places that around whatever code is given. Finally, the resulting code is so short that it can be one-lined using e, which is "run code from next argument".

See perlman:perlrun and perlman:perlop for more information on perl options and operators.

Drake Wilson

Update: D'oh! Corion had already pointed out -i. Oh well.


In reply to Re: Re: Re: Opening a file for reading or writing (was: Newbie) by premchai21
in thread Opening a file for reading or writing (was: Newbie) by padangboy

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.