0

I am newby to Bash, Ubuntu 16.04.

I have tons of files, which seems like:

aaaa1111
aaaa1112
aaaa1113
aaaa1114 ...

aaab1111
aaab1112
aaab1113
aaab1114 ...

aaac1111 
aaac1112 ... (and so on ...)

Anyway, the pattern is 4 characters + and digits. All I want to do is making the directory based on the 4 characters, and putting the corresponding files into the directory.

for instance,

aaaa1111
aaaa1112
aaaa1113
aaaa1114 ...

will be put into the directory of aaaa.

aaab1111
aaab1112
aaab1113
aaab1114 ...

will be put into the directory of aaab.

I tried to 'sed', 'mv', others, but didn't work out well.

New contributor
newkis is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
  • Are all the files in the same directory? There are other files that you want to exclude? – guillermo chamorro Aug 13 at 23:27
1
for file in [a-z][a-z][a-z][a-z][0-9][0-9][0-9][0-9]; do
    mkdir -p "${file:0:4}" && mv "$file" "${file:0:4}"
done

The for-loop iterates over the filenames in the current directory with four characters and four digits and assigns one filename to variable file in each step.

mkdir creates the target directory. Using flag -p prevents an error message if the directory already exists and ${file:0:4} leaves the first four characters of the current filename. If the command is successful the file is moved to this directory.

  • Good point, thanks! I combined both commands with &&. This should make the mv safer. – Freddy Aug 14 at 1:19
  • It it awesome, exactly what I wanted! – newkis Aug 14 at 22:13
0

I think this would do it:

cd your_source_dir || exit

for file in *; do
  if [[ $(echo "$file" | grep -Pw "[a-z]{4}[0-9]{4}") ]]; then
    dir="${file:0:4}"
    [[ -d "$dir" ]] || mkdir "$dir"
    [[ -f "$file"]] && mv "$file" "$dir/"
  fi
done
  • Thank you so much! – newkis Aug 15 at 5:46

Your Answer

newkis is a new contributor. Be nice, and check out our Code of Conduct.

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.