0

I have a bunch of files in Unix Directory :

  test_XXXXX.txt  
  best_YYY.txt   
  nest_ZZZZZZZZZ.txt

I need to rename these files as

  test.txt   
  best.txt   
  nest.txt

I am using Ksh on AIX .Please let me know how i can accomplish the above using a Single command .

Thanks,

pchegoor
  • 386
  • 1
  • 5
  • 14

2 Answers2

0

If this is a one time (or not very often) occasion, I would create a script with

$ ls > rename.sh
$ vi rename.sh
:%s/\(.*\)/mv \1 \1/
(edit manually to remove all the XXXXX from the second file names)
:x
$ source rename.sh

If this need occurs frequently, I would need more insight into what XXXXX, YYY, and ZZZZZZZZZZZ are.


Addendum

Modify this to your liking:

ls | sed "{s/\(.*\)\(............\)\.txt$/mv \1\2.txt \1.txt/}" | sh

It transforms filenames by omitting 12 characters before .txt and passing the resulting mv command to a shell.

Beware: If there are non-matching filenames, it executes the filename—and not a mv command. I omitted a way to select only matching filenames.

wallyk
  • 56,922
  • 16
  • 83
  • 148
  • Let me then say this : Remove the last 12 characters before the .txt in the Filenames. – pchegoor Jul 11 '13 at 19:12
  • I was probably thinking how this could be done for the Last n characters before the Extension .txt , where n is variable. But to be specific it is the last 12 characters.Also this has to done often. – pchegoor Jul 11 '13 at 19:16
  • @user2417881: I have amended my answer. Note that it is limited in scope. – wallyk Jul 11 '13 at 19:54
0

In this case, it seems you have an _ to start every section you want to remove. If that's the case, then this ought to work:

for f in *.txt
do
  g="${f%%_*}.txt"
  echo mv "${f}" "${g}"
done

Remove the echo if the output seems correct, or replace the last line with done | ksh.

If the files aren't all .txt files, this is a little more general:

for f in *
do
  ext="${f##*.}"
  g="${f%%_*}.${ext}"
  echo mv "${f}" "${g}"
done
twalberg
  • 59,951
  • 11
  • 89
  • 84
  • Thanks for your reply. How do i extend your code to a situation where i have to remove the last 12 chracters before the extension .txt for eg . – pchegoor Jul 11 '13 at 20:16
  • If it's exactly 12, `${f%????????????}` (12 `?`s) will work after you've already stripped off the extension, if your `ksh` is new enough... Or maybe `${f%{12}(?)}`. These are all newer features in some versions of `ksh` though, so check `man ksh` on your system for more info... – twalberg Jul 11 '13 at 20:24