Script to change basename with without changing ex

2019-08-24 03:02发布

I have several files with a.dat, a.txt, a.mp3, b.dat, b.txt, b.mp3, b.zip, b.rar, c.mp3 and so on. I want to rename all files with basename "a" to basename "x".

Such that files become x.dat, x.txt, x.mp3, b.dat,b.txt,b.mp3,b.zip,b.rar,c.mp3` and so on.

In Linux this can be done via terminal but requires lot of typing. I want a script to do the task for me.

3条回答
祖国的老花朵
2楼-- · 2019-08-24 03:13

I ll suggest a way, I think this could work. This is a little weird way I think, don't laugh. 10th std math.

First you grep all the names in the folder using the combination of ls and grep command

  • ls | grep ^a this will list you with all the files with a as the first letter. You can use a regular expression with this if you need only files with a as the name.

  • Read the file names one by one with a while loop

  • Store the file name into a variable (say $name1).And using sed and awk, extract the second part of the filename(ie. remove the dots into spaces and print the second coloumn) store this in another variable (say $extn).

  • you can rename the files using the first name stored in the variable ($name1) for specifying which file and use the second variable to specify the extension ($extn) for the new name...

This is a loooong route :) I am sure this will work. Try it. Consider this as the algorithm and script.I am sorry that I dint provide a script.Little bit lazy.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-24 03:20

There is a small program called mmv which does the job:

$ touch a.dat a.txt a.mp3 b.dat b.txt b.mp3 b.zip b.rar c.mp3
$ mmv "a.*" "x.#1"
$ ls 
b.dat  b.mp3  b.rar  b.txt  b.zip  c.mp3  x.dat  x.mp3  x.txt

mmv comes with typically any Linux distribution.

查看更多
成全新的幸福
4楼-- · 2019-08-24 03:24

You don't need a script when you have the rename (or prename on some systems) command.

It allows groups of files to be renamed using arbitrarily complex Perl regular expressions:

pax> ll qq*
-rwxr-xr-x 1 pax pax 4574 Apr 13 17:03 qq
-rw-r--r-- 1 pax pax  213 Apr 13 17:03 qq.c
-rw-r--r-- 1 pax pax  804 Apr  6 12:23 qq.cpp
-rw-r--r-- 1 pax pax  258 Apr  5 21:33 qq.m
-rw-r--r-- 1 pax pax  904 Apr  6 10:35 qq.o
-rw-r--r-- 1 pax pax  241 Apr  6 10:50 qq.py
-rw-r--r-- 1 pax pax  769 Apr  7 09:47 qq.txt

pax> rename 's/qq/xyzzy/' qq*

pax> ll qq*
ls: cannot access qq*: No such file or directory

pax> ll xyzzy*
-rwxr-xr-x 1 pax pax 4574 Apr 13 17:03 xyzzy
-rw-r--r-- 1 pax pax  213 Apr 13 17:03 xyzzy.c
-rw-r--r-- 1 pax pax  804 Apr  6 12:23 xyzzy.cpp
-rw-r--r-- 1 pax pax  258 Apr  5 21:33 xyzzy.m
-rw-r--r-- 1 pax pax  904 Apr  6 10:35 xyzzy.o
-rw-r--r-- 1 pax pax  241 Apr  6 10:50 xyzzy.py
-rw-r--r-- 1 pax pax  769 Apr  7 09:47 xyzzy.txt
查看更多
登录 后发表回答