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

Given the following file:
353513_3.REPT
can somebody rewrite this as a shorter one-liner?
perl -e "@m=glob('*');@m = grep{m/\d+_\d+\.REPT/g} @m; foreach(@m){$s= +$_;$s=~s/REPT/ERR/; rename($_,$s);}"
This second attempt did not shorten it by much:
perl -e "foreach(grep {m/(\d+_\d+)\.REPT/g} glob('*')){$aa=$_; rename( +$aa,$_) if $_=~s/REPT/ERR/;};"

pardon my stupidity

Replies are listed 'Best First'.
Re: Shorter one-liner?
by suaveant (Parson) on Jul 24, 2001 at 22:16 UTC
    perl -e 'for(<*>) { rename($_,"$1.ERR") if /^(\d+_\d+)\.REPT$/}'

    Update can make it even shorter like this...

    perl -e 'for(<*>){`mv $_ $1.ERR`if/^(\d+_\d+)\.REPT$/}'
    but I'd go with the first one... :)

                    - Ant

      Hello,

      Here is one with 2 chars less :-) perl -e 'map{`mv $_ $1.ERR`if/^(\d+_\d+)\.REPT$/}<*>' Or taking 2 more off: perl -e '/^(\d+_\d+)\.REPT$/&&`mv $_ $1.ERR`for<*>' But I wouldn't use it either.

      Aziz,,,

      Doi! The grep was totally redundant. Thanks.

      Celebrate Intellectual Diversity

Re: Shorter one-liner?
by snafu (Chaplain) on Jul 25, 2001 at 00:17 UTC
    Well, I am no expert and I certainly am still learning my one liners. However, the thing that immediately popped out at me is:

  • Your grep regex probably doesn't need to be so specific. According to the file you gave in your example and the fact that you were no more specific than what you gave in your example, then I would break that grep() into a really basic pattern match so that the file(s) would be picked up. This makes your one-liner a little bit shorter. However, the regex also makes the one-liner less specific if you have files that have other patterns that need to be matched.
  • I changed it to use map which I am quite new at but am really growing to like. Thing is I think that the regex portion of my dealy here can be improved upon but I couldn't fix it quick enough before I had to get back to work.
  • perl -e 'map{($a=$_)=~s/REPT/ERR/,rename($_,$a)}glob("*.REPT")'

    Yours first one liner was about 83 characters (minus a few because I had to escape some of the special characters...)

    perl -e '$var = "\@m=glob(\"*\");\@m = grep{m/\d+_\d+\.REPT/g} \@m; fo +reach(\@m){$s=$_;$s=~s/REPT/ERR/; rename($_,$s);}";print length($var) +,"\n";' 83

    Mine has 45 (same with mine..minus a couple characters since Im not sure if Perl counted the escapes)
    perl -e '$var = "map{($a=$_)=~s/REPT/ERR/,rename($_,$a)}glob(\"*.REPT\ +")";print length($var),"\n";' 45

    [qadmin@concon qw]$ ls -1 *REPT *ERR ls: *ERR: No such file or directory 353513_3.REPT 42342_12.REPT 442342_2.REPT [qadmin@concon qw]$ perl -e 'map{($a=$_)=~s/REPT/ERR/,rename($_,$a)}gl +ob("*.REPT")' [qadmin@concon qw]$ ls -1 *REPT *ERR ls: *REPT: No such file or directory 353513_3.ERR 42342_12.ERR 442342_2.ERR [qadmin@concon qw]$

    ----------
    - Jim