removing extensions in subdirectories

北慕城南 提交于 2020-01-05 04:42:16

问题


I need to remove the extension ".tex":

./1-aoeeu/1.tex
./2-thst/2.tex
./3-oeu/3.tex
./4-uoueou/4.tex
./5-aaa/5.tex
./6-oeua/6.tex
./7-oue/7.tex

Please, do it with some tools below:

  1. Sed and find

  2. Ruby

  3. Python

My Poor Try:

$find . -maxdepth 2 -name "*.tex" -ok mv `sed 's@.tex@@g' {}` {} +

回答1:


A Python script to do the same:

import os.path, shutil

def remove_ext(arg, dirname, fnames):
    argfiles = (os.path.join(dirname, f) for f in fnames if f.endswith(arg))
    for f in argfiles:
        shutil.move(f, f[:-len(arg)])

os.path.walk('/some/path', remove_ext, '.tex')



回答2:


One way, not necessarily the fastest (but at least the quickest developed):

    pax> for i in *.c */*.c */*/*.c ; do
    ...> j=$(echo "$i" | sed 's/\.c$//')
    ...> echo mv "$i" "$j"
    ...> done

It's equivalent since your maxdepth is 2. The script is just echoing the mv command at the moment (for test purposes) and working on C files (since I had no tex files to test with).

Or, you can use find with all its power thus:

    pax> find . -maxdepth 2 -name '*.tex' | while read line ; do
    ...> j=$(echo "$line" | sed 's/\.tex$//')
    ...> mv "$line" "$j"
    ...> done




回答3:


There's an excellent Perl rename script that ships with some distributions, and otherwise you can find it on the web. (I'm not sure where it resides officially, but this is it). Check if your rename was written by Larry Wall (AUTHOR section of man rename). It will let you do something like:

find . [-maxdepth 2] -name "*.tex" -exec rename 's/\.tex//' '{}' \;

Using -exec is simplest here because there's only one action to perform, and it's not too expensive to invoke rename multiple times. If you need to do multiple things, use the "while read" form:

find . [-maxdepth 2] -name "*.tex" | while read texfile; do rename 's/\.tex//' $texfile; done

If you have something you want to invoke only once:

find . [-maxdepth 2] -name "*.tex" | xargs rename 's/\.tex//'

That last one makes clear how useful rename is - if everything's already in the same place, you've got a quick regexp renamer.




回答4:


Using "for i in" may cause "too many parameters" errrors

A better approach is to pipe find onto the next process.

Example:

find . -type f -name "*.tex" | while read file
do
    mv $file ${file%%tex}g
done

(Note: Wont handle files with spaces)




回答5:


Using bash, find and mv from your base directory.

 for i in $(find . -type f -maxdepth 2 -name "*.tex"); 
 do 
    mv $i $(echo "$i" | sed 's|.tex$||'); 
 done

Variation 2 based on other answers here.

find . -type f -maxdepth 2 -name "*.tex" | while read line; 
do 
   mv "$line" "${line%%.tex}";  
done

PS: I did not get the part about escaping '.' by pax...



来源:https://stackoverflow.com/questions/1204617/removing-extensions-in-subdirectories

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