Changing file extensions for all files in a direct

2019-01-30 06:28发布

I have a directory full of files with one extension (.txt in this case) that I want to automatically convert to another extension (.md).

Is there an easy terminal one liner I can use to convert all of the files in this directory to a different file extension?

Or do I need to write a script with a regex?

9条回答
男人必须洒脱
2楼-- · 2019-01-30 06:35
    cd $YOUR_DIR
    ls *.txt > abc
    mkdir target // say i want to move it to another directory target in this case
    while read line
    do 
    file=$(echo $line |awk -F. '{ print $1 }')
    cp $line target/$file.md  // depends if u want  to move(mv) or copy(cp)
    done < abc
查看更多
ら.Afraid
3楼-- · 2019-01-30 06:39

Alternatively, you could install the ren (rename) utility

brew install ren

ren '*.txt' '#1.md'

If you want to rename files with prefix or suffix in file names

ren 'prefix_*.txt' 'prefix_#1.md'
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-30 06:41

Based on the selected and most accurate answer above, here's a bash function for reusability:

function change_all_extensions() {
    for old in *."$1"; do mv $old `basename $old ."$1"`."$2"; done
}

Usage:

$ change_all_extensions txt md

(I couldn't figure out how to get clean code formatting in a comment on that answer.)

查看更多
Ridiculous、
5楼-- · 2019-01-30 06:42

For those of you guys who are not really good in programming you can check out this article on wiki how.
It shows many method of doing it that doesn't involve coding
and you can also check out this blogpost on changing file extensions.
It contains a console application that does all the stuffs for you.

查看更多
贼婆χ
6楼-- · 2019-01-30 06:48

You could use something like this:

for old in *.txt; do mv $old `basename $old .txt`.md; done

Make a copy first!

查看更多
淡お忘
7楼-- · 2019-01-30 06:52

No need to write a script for it just hit this command

find ./ -name "*.txt" | xargs -I '{}' basename '{}' | sed 's/\.txt//' | xargs -I '{}' mv '{}.txt'  '{}.md'
查看更多
登录 后发表回答