3

I am attempting to move a sub-directory from one parent directory to another for hundreds of instances, while changing the name of the sub-directory during the move. My directories are a set of numbers:

1000, 1001, 1002, 1003, ..., 1998, 1999

Each directory has a sub-folder called 'old' (e.g., 1000/old), which I want to move into the next incremented directory (and rename the sub-folder).

For example, I want to move '1000/old' to '1001/new'.

I've tried using xargs, which I' new to, so I'm not sure I'm going in the right direction. I think what I want is something like:

find 1* -name 'old' | xargs -i -t mv {} <dir+1>/new

I'm just not sure how to implement incrementing (the dir+1 bit).

I've also tried to implement a modification of the accepted answer to this question, but my modification is also not working properly (I'm using ls to test the code before I actually start moving/renaming directories):

#!/bin/bash
for x in 1*; do
  ls -d "$x/old" "${x}$i/new"
  ((++i))
done

The issue with the above is that the next directory becomes 10001, 10002, etc instead of 1001, 1002.

Any suggestions are much appreciated.

1 Answer 1

2

Shells treat strings representing integers in decimal as integers. If you have a directory whose name contains only digits with no leading zeros, you have a number and you can perform arithmetic on it.

for d in 1*; do
  mv "$d/old" "$((d+1))/new"
done

You can make the script more robust and only perform the move if the old subdirectory actually exists, and create the destination if necessary.

for d in 1*; do
  if [ -d "$d/old" ]; then
    mkdir -p "$((d+1))"
    mv "$d/old" "$((d+1))/new"
  fi
done

find isn't useful here since you aren't traversing subdirectories recursively.

3
  • mv "$d/old" -T "$((d+1))/new" looks better
    – Costas
    Commented Mar 28, 2015 at 0:15
  • 1
    @Costas Does it? Why? It requires GNU mv and I see zero benefit in this situation. Commented Mar 28, 2015 at 0:29
  • @Gilles Thank you. I didn't realize that a directory name made up of digits wouldn't be a string. Your answer is very simple and very helpful!
    – WillaB
    Commented Mar 30, 2015 at 21:54

You must log in to answer this question.

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