Hello DaniWeb Users,

I need some help how I can change a file name but not the file extension.

Doing it one by one is pain.

mv file1.gr2 test1.gr2

doing this will need a lot of time.

I been searching for an hour

find . -name "*.gappedPeak" -exec sh -c 'mv "$1" "${1%.gappedPeak}.bed"' _ {} \;

this command change the file extension but not the file name.

Please help me how I can change file name.

Actually I would just cut some of the file name

Example of my file:

Test_Sample_d01_2016f00300.gr2
Test_Sample_d01_2016f00600.gr2
Test_Sample_d01_2016f00900.gr2
Test_Sample_d01_2016f01200.gr2
Test_Sample_d01_2016f01500.gr2
....
Test_Sample_d01_2016f30000.gr2

I would like to remove this Test_Sample_d01_ without changing the file extension.

This python script may work. Python is very powerful for such tasks

#!/usr/bin/env python
# -*-coding: utf8-*-
'''doc
'''
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from argparse import ArgumentParser
import os.path

if __name__ == '__main__':
    p = ArgumentParser(description='change names of some files')
    p.add_argument('dir', metavar='DIR', help='directory containing files to move')
    args = p.parse_args()
    prefix = 'Test_Sample_d01_'
    for f in list(os.listdir(args.dir)):
        if f.startswith(prefix):
            src = os.path.join(args.dir, f)
            dst = os.path.join(args.dir, f[len(prefix):])
            if os.path.exists(dst):
                print("File '{}' exists. Skipping '{}'".format(dst, f))
                continue
            os.rename(src, dst)

This will get you what you want.... working from the input list in your post:

find . -name "*.gr2" -exec sh -v 'mv $1 $(echo $1 | cut -f 4 -d"_")' _ {} \;

Hello Sir Gribouillis,

I try to run the python test1.py (I save it as test1.py)

an error appear

usage: test1.py [-h] DIR
test1.py: error: too few arguments

Do I need to change anything to the code? PS: Sadly, I don't know how to code python. :(

Hello CimmerianX,

I try the code

find . -name "*.gr2" -exec sh -v 'mv $1 $(echo $1 | cut -f 4 -d"_")' _ {} \;

and error appear.

sh: 0: Can't open mv $1 ${echo $1 | cut -f 4 -d"_")
sh: 0: Can't open mv $1 ${echo $1 | cut -f 4 -d"_")
sh: 0: Can't open mv $1 ${echo $1 | cut -f 4 -d"_")
sh: 0: Can't open mv $1 ${echo $1 | cut -f 4 -d"_")
sh: 0: Can't open mv $1 ${echo $1 | cut -f 4 -d"_")

am I missing something or I doing it wrong? or do I need something? coz it says Can't open mv :(

Sorry for the late feedback :(

You need to pass an argument to the script

python test1.py /path/to/folder/containing/files

Sorry - my bad, its not a -v, its a -c

find . -name "*.gr2" -exec sh -c 'mv $1 $(echo $1 | cut -f 4 -d"_")' _ {} \;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.