1

My question is a bit different than:

Create directory using filenames and move the files to its repective folder

Since in the same folder I have two similar copy of each file like:

001.txt and 001(1).txt

.....

100.txt and 100(1).txt

For each two similar copies, create one folder and move both similar copies into one folder. 001.txt and 001(1).txt into 001 folder

Base on above question, but does't work. command from above question:

set -o errexit -o nounset
cd ~/myfolder
for file in *.txt
do
    dir="${file%.txt}"
    mkdir -- "$dir"
    mv -- "$file" "$dir"
done

Have tried:

set -o errexit -o nounset
cd ~/myfolder

for file in *(1).txt
do
    dir="${file%.txt}"
    mkdir -- "$dir"
    mv -- "$file" "$dir"
done

This command will create folder for each file.

Any suggestion to distinguish files like 001.txt and 001(1).txt, so we can select the desired file to create one folder, then run another command to archive the same goal?

1 Answer 1

1

You're nearly there. What you're missing is that you also need to try to strip the bracketed number from the filename to derive the directory:

#!/bin/sh
for file in *.txt
do
    dir="${file%.txt}"         # Remove suffix
    dir="${dir%(*)}"           # Remove bracketed suffix if present

    mkdir -p -- "$dir"         # Create if necessary
    mv -f -- "$file" "$dir"    # Move the file
done

You can prefix the mkdir and mv with echo to see what would happen before you action it.

4
  • This doesn't work, which just create the same result of having each folder for each file. but we would like to create one folder for each similar copy files. one folder for 001.txt and 001(1).txt where 001.txt and 001(1). txt have different content.
    – Maxfield
    Commented Aug 4, 2022 at 12:29
  • @johnsmith please update your question to make that clear. You have currently written "For each two similar copy, create one folders and move both similar file into the folder.", and that is what this code does. Commented Aug 4, 2022 at 12:33
  • @johnsmith I see your edit. My code does exactly what you ask for the example filenames you provide (item.txt and item(1).txt, etc.). Therefore, if it's not working for you, you need to give examples of the file names that work and those that do not. Commented Aug 4, 2022 at 13:45
  • Ok You bash script works great. when it was run as bash instead of copying the lines one by one. Thank you. Any ideal ? yes I was also doing the "set -o errexit -o nounset" command, not sure if there is the problem.
    – Maxfield
    Commented Aug 4, 2022 at 14:03

You must log in to answer this question.

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