Script to change basename with without changing extension in linux

这一生的挚爱 提交于 2019-12-11 15:35:37

问题


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.


回答1:


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.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/10138322/script-to-change-basename-with-without-changing-extension-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!