Find the answer to your Linux question:
Results 1 to 3 of 3
HI , Due to unsuccessful execution of a script all filenames under a directory have been changed . Say "Sample" is the directory.The original file names under this are sample1.txt ...
  1. #1
    Just Joined!
    Join Date
    Oct 2009
    Posts
    2

    Script to change all filenames in a directory recursively

    HI ,

    Due to unsuccessful execution of a script all filenames under a directory have been changed .

    Say "Sample" is the directory.The original file names under this are

    sample1.txt
    sample2.txt
    sample3.txt

    Now these have been changed to

    sample1.txt_new
    sample2.txt_new
    sample3.txt_new

    so i want to rename them to original names.I require a small script which will remove "_new" in all the files present recursively under a directory.

    Thanks in advance

  2. #2
    Linux Newbie birdman's Avatar
    Join Date
    Mar 2006
    Location
    Ireland
    Posts
    141
    If I have a directory like so:
    Code:
    bash-3.2$ ls -R
    .:
    1.other  1.txt_new  2.txt_new  3.txt_new  new  test.sh
    
    ./new:
    2.other  sample1.txt_new  sample2.txt_new  sample3.txt_new
    Inside test.sh is:
    Code:
    #!/bin/sh
    
    for a in `find -name \*.txt_new`
    do
            newname=`echo $a | sed "s/txt_new/txt/g"`
            mv $a $newname
    done
    When I run test.sh the following is outputted:
    Code:
    bash-3.2$ ls -R
    .:
    1.other  1.txt  2.txt  3.txt  new  test.sh
    
    ./new:
    2.other  sample1.txt  sample2.txt  sample3.txt
    It won't cover all your bases (i.e. if txt_new forms part of your filename as well) but it should probably work

  3. #3
    Linux Guru
    Join Date
    Oct 2007
    Location
    Tucson AZ
    Posts
    1,939
    Tried the following rename command with some files I created and it worked:

    Code:
    rename txt_new txt"" sample*
    I expect this will affect any files beginning with "sample".

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...