开发者

List files that have the same first 16 characters

I want to write a bash script that I can run in a directory and that will do the following:

  • Go through all subdirectories (recursively)
  • If there are two files in the same given subdirectory whose filenames have the same first 16 characters (e.g. "YourTestFileNameHey.jpg" and "YourTestFileNameFoo.png"), output their file names (or move one of them to a diffe开发者_如何学Gorent location).

Does anyone know how to do this?


Do yourself a favor and use something else than bash for a task that complex. My own first choice would be Perl, but if you know any general-purpose programming language, it will be easier and more maintainable there than in pure shell.


I don't know if this will do the job for you, but you can base yourself on the following script:

#!/bin/bash
cd "$1"
for i in *; do j=`echo $i | cut -c 1-16`; echo $1/$i\|$j;done | awk -F\| 'seen[$
2]++ == 1 { printf("echo \"%s\"", $1) | "sh" }'

It will list every second file that has the same first 16 characters as another file in the same directory. You could easily replace the echo command inside printf("echo \"%s\"", $1) by a mv command.

Now, if you want to use this script in all subdirectories under a specific directory, let's call it mydir, you could do that with the find command like this, assuming you saved the above script in a file called myscript which resides in the same directory as mydir:

find mydir -type d -exec ./myscript {} \;

Does this help?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜