I am working with 800 txt files in the same directory. I would like to rename all these files as follows:
1.txt
2.txt
…
799.txt
800.txt
How do you think this would be possible with Julia?
Thanks in advance,
Bruno
I am working with 800 txt files in the same directory. I would like to rename all these files as follows:
1.txt
2.txt
…
799.txt
800.txt
How do you think this would be possible with Julia?
Thanks in advance,
Bruno
You can get a list of file names using readdir
. From there you can iterate over all the files and call mv
to rename them.
files = readdir()
txt_files = filter(endswith(".txt"),files)
for (i,file) in enumerate(txt_files)
mv(file,"$(i).txt")
end
Dear Michael,
Thank you very much.
Cheers
Bruno
Dear Michael,
I apologize for the many questions, but I had a problem. Taking into account the first 20 files of my list (with 800 txt files), the txt-files array is:
Blockquote
[“I_0,6_0,2_20_10_1.txt”, “I_0,6_0,2_20_10_10.txt”, “I_0,6_0,2_20_10_2.txt”, “I_0,6_0,2_20_10_3.txt”, “I_0,6_0,2_20_10_4.txt”, “I_0,6_0,2_20_10_5.txt”, “I_0,6_0,2_20_10_6.txt”, “I_0,6_0,2_20_10_7.txt”, “I_0,6_0,2_20_10_8.txt”, “I_0,6_0,2_20_10_9.txt”, “I_0,6_0,2_20_5_1.txt”, “I_0,6_0,2_20_5_10.txt”, “I_0,6_0,2_20_5_2.txt”, “I_0,6_0,2_20_5_3.txt”, “I_0,6_0,2_20_5_4.txt”, “I_0,6_0,2_20_5_5.txt”, “I_0,6_0,2_20_5_6.txt”, “I_0,6_0,2_20_5_7.txt”, “I_0,6_0,2_20_5_8.txt”, “I_0,6_0,2_20_5_9.txt”]
Blockquote
Unfortunately, the files are not in the order in which they appear in the folder. They are sorted taking into consideration the digits.
How could I use the files in the same order in which they appear in the directory? I tried several times without success.
You can sort on whatever you like using Base.stat
and the by
argument to sort
.
https://docs.julialang.org/en/v1/base/file/#Base.stat
https://docs.julialang.org/en/v1/base/sort/#Base.sort
For example:
sort(readdir("."); by=f->stat(f).inode)
Dear Jeff,
Thanks a lot.
Cheers,
Bruno
I think you can also do readdir(dir, sort = false)
Thanks a lot, Jules. Cheers.
const BASEDIR="/home/hillel/workjulspace/testdata/B"
files = readdir(BASEDIR, join=true, sort = true)
filenames = readdir(BASEDIR,sort = true)
#println(files)
#println(filenames)
#println(files)
img_files = filter(endswith(".png"),files)
for (i,file) in enumerate(img_files)
#println(i)
#println(file)
mv(file,"/home/hillel/workjulspace/testdata/B/BB_$(filenames[i])")
end
I think this might not be what you want?
By filtering the files array you also change its index.
using Logging
ENV["JULIA_DEBUG"] = Main
const BASEDIR="/home/hillel/workjulspace/testdata/B"
files = readdir(BASEDIR, join=true)
png_files = filter(endswith(".png"), files)
for file in png_files
new_filename = join(["BB", basename(file)], "_")
new_file = joinpath(BASEDIR, new_filename)
@debug "moving file" file new_file
mv(file, new_file)
end