9

How can I rename all *.txt in a directory to *.csv files in the terminal (Mavericks). I tried following inside the directory:

mv *.txt *.csv
1
  • This can be done nicely in AppleScript. Then AppleScript can be called with the Terminal command osascript. Commented Aug 29, 2014 at 12:46

4 Answers 4

12

You need to loop over all files

for f in *.txt; do
    mv "$f" "${f%.txt}.csv"
done

If you have files with names starting with a . as well you might need to run

for f in *.txt .*.txt; do
    [[ -f "$f" ]] && mv "$f" "${f%.txt}.csv"
done
0
1

This also works well:

# change to the Zsh
zsh

# load the built-in zmv function
autoload -U zmv

# rename the files
zmv '(*).txt' '$1.csv'
0
0
ls *.txt |awk '{print "mv "$1" " substr($1,1,(index($1,".txt")))"csv"}' |sh

Command explanation:

ls *.txt lists files ending with txt

| awk '{print "mv "$1" " substr($1,1,(index($1,".txt")))"csv"} prints the command that allows to rename the previous files listed with txt to csv

| sh executes the previously printed command, thus effectively renaming the files

Note: if you want to list all files including hidden files (those starting with .) use ls -a *.txt instead

0
0

If you have a huge number of files inside the directory, then even the ls*.txt command can fail, in that scenario, the below command can help:

find . -maxdepth 1 -name '*.txt' | sed 's/^\.\///g' | while read f1 ;do mv -v "$f1" "${f1%.*}.csv" ; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .