I'm using rsync and the flags -nPaAXz ~/ to check which files are going to be copied.

This is far too verbose to make any sense of.

How could I filter the output so I view the list of files/folders that are going to be copied to a certain depth, eg:

1 folder deep


2 folders deep


The following grep will restrict rsync's verbose output to a depth of 2 folders:

rsync -nPaAXz src_dir dst_dir | grep -E '^/?([^/]+/?){0,2}$'

Change the {0,2} above to {0,3} to filter out 3 folders deep. {0,4} will filter out 4 folders deep etc.

  • Great answer, thanks! I think the perfect solution would have to be more complicated though. With this solution, if a particular folder didn't have any files at the relevant depth or shallower, the path would be filtered out completely by the grep. What you would want is for each path to be truncated to the correct depth, and then not to print any duplicate paths. Would you maybe need to use awk to do that? – Acorn Mar 8 '11 at 21:27
  • Where in this answer is depth addressed? {0,2} would be finding a minimum of none with a maximum of 2 for the pattern ([^/]+/?). Genuine question. – kayleeFrye_onDeck Jul 29 '16 at 23:37

This command takes each path and truncates it to n folders deep (defined in the \{0,n\} section of the sed command and the {0,n} section of the grep command). It's then piped into uniq to filter out the duplicates.

rsync -nPaAXz src_dir dst_dir | sed -n 's@^\(\([^/][^/]*/\)\{0,2\}\).*@\1@p' | uniq

The same thing can also be achieved using grep:

rsync -nPaAXz src_dir dst_dir | grep -oE "^([^/]+/){0,2}"

Although the above wont work with GNU grep versions < 2.5.3 due to a bug.


In this case, you just want to filter the output, and you don't actually care about reusing the values in any way. That's easy, then: just grep out lines that contain more slashes than you want.

rsync -nPaAXz src_dir dst_dir | cut -d "/" -f 1-4 | awk '!x[$0]++'

cut removes everything after 4 folders deep paths and awk removes duplicates.

Your Answer

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.