efxtv

Moving files from multiple numbered folders into one - using Bash loop and xargs

Jul 13th, 2025
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | Cybersecurity | 0 0
  1. # 🔁 Moving files from multiple numbered folders into one - using Bash loop and xargs
  2.  
  3. Note: The `i` variable in a `for` loop and the `{}` placeholder used with `xargs -I{}` serve a similar purpose -
  4. both are used to iterate over values and substitute them within the command being executed.
  5.  
  6. ✅ Cleaner and simpler version using Bash for-loop:
  7.  
  8. for i in {10..29}; do
  9. mv "Folder-1-0$i"/* \
  10. "Folder-1-001/"
  11. done
  12.  
  13. ####################################################################################
  14. 🔹 For loop breakdown:
  15. - `for i in {10..29}; do` : Loops through numbers from 10 to 29 (inclusive) using brace expansion.
  16. - `$i` : Holds the current number in each iteration.
  17. - `do ... done` : Body of the loop that runs your desired commands.
  18.  
  19. This method is clean, fast, and highly readable for ranges with known numeric patterns.
  20. ####################################################################################
  21.  
  22. ✅ Alternative using seq and xargs:
  23.  
  24. seq 10 29 | xargs -I{} mv "Folder-1-0{}"/* \
  25. "Folder-1-001/"
  26.  
  27. ####################################################################################
  28. 🔹 xargs breakdown:
  29. - `seq 10 29` : Generates a list of numbers from 10 to 29.
  30. - `xargs -I{}` : For each number, replaces `{}` in the command with the current number.
  31. - Each `mv` command moves the contents of one numbered folder into the target folder.
  32.  
  33. Useful when working with piped input or dynamic file lists from other commands.
  34. ####################################################################################
  35.  
  36. Bonus:
  37. Extract multiple zip files in PWD (using for loop):
  38. ####################################################################################
  39. for file in *.zip; do
  40. dir="${file%.zip}"
  41. unzip "$file" -d "$dir"
  42. done
  43. ####################################################################################
  44.  
Advertisement
Add Comment
Please, Sign In to add comment