1833229 Members
2892 Online
110051 Solutions
New Discussion

Replacing the file name

 
GOPI KRSNA
Occasional Contributor

Replacing the file name

Hi,

In one dir i have files like:

0345_ad.csv
0346_ad.csv
1234_ad.csv
3456_ad.csv
0345_ng.csv
0346_ng.csv
1234_ng.csv
3456_ng.csv
3908_21.csv

etc..

Out of these files i want to change the file having ...._ng.csv to ...._NG.csv and same for ...._ad.csv to ...._AD.csv.

Can someone suggest how to do this?

Thanks

7 REPLIES 7
Hakki Aydin Ucar
Honored Contributor

Re: Replacing the file name

izad
Honored Contributor

Re: Replacing the file name

Hi Gopi,

Run the following from your directory.

for i in `ls *_ng.csv | cut -f1 -d_`;do mv ${i}_ng.csv ${i}_NG.csv;done

for i in `ls *_ad.csv | cut -f1 -d_`;do mv ${i}_ad.csv ${i}_AD.csv;done

HTH,

REgards,
I hate quotations. Tell me what you know !
Hein van den Heuvel
Honored Contributor

Re: Replacing the file name

That's one of my favourite PERL tasks to show to noobies.

untested (in a rush):

First see if you can find and transform what you need with a PRINT

perl -e 'for (<*>){ $old=$_; m/_(.*)\./; $new = $`.uc($1).$'; print "$old, $new\n" }' | more

Next edit command to use RENAME for real.

perl -e 'for (<*>){ $old=$_; m/_(.*)\./; $new = $`.lc($1).$'; rename $old, $new }'

$1 is thestring matched between the parens ().
The $` is the'pre-match variable, $' = post-match.

Hein.
Hein van den Heuvel
Honored Contributor

Re: Replacing the file name

That should be uc($1) for uppercase not lc($1) which would make it lowercase.

Hein.
James R. Ferguson
Acclaimed Contributor

Re: Replacing the file name

Hi:

Hein's untested solution needs a minor correction as it loses the "_" and ".' characters. It also misses constructing a new filename when the old one doesn't match the pattern needed.

This variation corrects that and only prints or renames files that match the pattern:

#!/usr/bin/perl
for (<*>) {
$old = $new = $_;
m/(_.*\.)/ and $new = $`.uc($1).$';
print "$old $new\n" unless $new eq $old;
}

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: Replacing the file name

>izad: Run the following from your directory.

You could improve this by using only one loop and using sed:
for file in *_ng.csv *_ad.csv; do
mv $file $(echo $file | sed -e 's/_ng/_NG/' -e 's/_ad/_AD/')
done

(Check first by adding "echo " before the mv.)
Fredrik.eriksson
Valued Contributor

Re: Replacing the file name

Or if you don't wish to muck about with regexps and what not. Since your files only contains letters that you want uppercased.

for i in /file/path/*.csv; do
mv "$i" "$(echo $i | tr a-z A-Z)"
done

Best regards
Fredrik Eriksson