Search code examples
linuxsplitrenamenested-loops

rename files which produced by split


I splitted the huge file and output is several files which start by x character.

I want to rename them and make a list which sorted by name like below:

part-1.gz

part-2.gz

part-3.gz ...

I tried below CMD:

for (( i = 1; i <= 3; i++ )) ;do for f in `ls -l | awk '{print $9}' | grep '^x'`; do mv $f part-$i.gz ;done ; done;

for f in `ls -l | awk '{print $9}' | grep '^x'`; do for i in 1 .. 3 ; do mv -- "$f" "${part-$i}.gz" ;done ; done;

for i in 1 .. 3 ;do for f in `ls -l | awk '{print $9}' | grep '^x'`; do mv -- "$f" "${part-$i}.gz" ;done ; done;

for f in `ls -l | awk '{print $9}' | grep '^x'`; do mv -- "$f" "${f%}.gz" ;done


Solution

  • Tip: don't do ls -l if you only need the file names. Even better, don't use ls at all, just use the shell's globbing ability. x* expands to all file names starting with x.

    Here's a way to do it:

    i=1; for f in x*; do mv $f $(printf 'part-%d.gz' $i); ((i++)); done
    

    This initializes i to 1, and then loops over all file names starting with x in alphabetical order, assigning each file name in turn to the variable f. Inside the loop, it renames $f to $(printf 'part-%d.gz' $i), where the printf command replaces %d with the current value of i. You might want something like %02d if you need to prefix the number with zeros. Finally, still inside the loop, it increments i so that the next file receives the next number.

    Note that none of this is safe if the input file names contain spaces, but yours don't.