acc427us has asked for the wisdom of the Perl Monks concerning the following question:

Your mighty wizdom is needed. How do I remove a simple colon (:) from an ascii file. Like to remove teh colon from 09:23:00. I'd like it to say 0923. I've tried sed s/\://g and it leaves it there.

Replies are listed 'Best First'.
Re: removing colons
by davido (Cardinal) on Oct 07, 2003 at 02:49 UTC
    First, there is no need to backslash (escape) the colon. It's not a metacharacter. However, that isn't your problem.

    When I try the simple code:

    use strict; use warnings; while (<DATA>) { s/://g; print $_; } __DATA__ 9:23:00 02:23:34
    I find that colons are indeed removed. So the problem is probably related to how you're handling the file IO.

    Unless you're using the -i command line option, you can't edit the file in place. You need to open the original file for input, open a temporary file for output, read the orig, get rid of the colons, write the results to the temp file, and then move the temp file to replace the orig.

    That ought to do the trick.

    Of course if you're just trying to remove colons from times, and preserve them elsewhere, this solution is too aggressive. But your original question didn't really specify.


    Dave


    "If I had my life to do over again, I'd be a plumber." -- Albert Einstein
Re: removing colons
by Roger (Parson) on Oct 07, 2003 at 02:49 UTC
    Try to do this instead -
    sed s/://g file.txt > newfile.txt
    And the newfile.txt should have the colons removed.

      Recent versions of GNU sed have stolen Perl's -i option, so you can say
      sed -i 's/://g' file.txt
      and have file.txt updated in-place.

      Makeshifts last the longest.

Re: removing colons
by Zaxo (Archbishop) on Oct 07, 2003 at 02:48 UTC

    One of many many ways, from the command line perl -pi -e's/\b(\d\d):(\d\d):\d\d\b/$1$2/g;' filename.ext \b is a word boundary, which helps narrow the selection. \d are digits, and we capture the significant ones with parens. That makes them available as $1, $2 in the substitution string. The /g modifier makes the substitution for all instances on a line.

    After Compline,
    Zaxo