根据名称查找文件并通过重命名同时移动它们

Pan*_*dya 5 command-line find rename mv

考虑我有根据年份命名的目录,并根据主题代码包含 pdf 文件。

ls 输出是:

$ ls -l
total 32
drwxrwxrwx 1 root root 4096 Apr  8 08:52 May-June-2011
drwxrwxrwx 1 root root 4096 Apr  8 08:52 Nov-Dec-2011
drwxrwxrwx 1 root root 4096 Apr  8 20:36 Summer-2012
drwxrwxrwx 1 root root 4096 Apr  8 08:52 Summer-2013
drwxrwxrwx 1 root root 4096 Apr  8 08:52 Summer-2014
drwxrwxrwx 1 root root 4096 Apr  8 08:52 Winter-2012
drwxrwxrwx 1 root root 4096 Apr  8 08:52 Winter-2013
drwxrwxrwx 1 root root 4096 Apr  8 08:52 Winter-2014
Run Code Online (Sandbox Code Playgroud)

每个目录包含根据主题代码的 pdf 文件:-

ls -l May-June-2011/
total 808
-rwxrwxrwx 1 root root 104193 May  1  2011 161901.pdf
-rwxrwxrwx 1 root root 103380 May  1  2011 161902.pdf
-rwxrwxrwx 1 root root 115664 May  1  2011 161903.pdf
-rwxrwxrwx 1 root root  88953 May  1  2011 161904.pdf
-rwxrwxrwx 1 root root 179268 May  1  2011 161905.pdf
-rwxrwxrwx 1 root root 116158 May 24  2011 161906.pdf
-rwxrwxrwx 1 root root 106033 May  1  2011 161907.pdf
Run Code Online (Sandbox Code Playgroud)

换句话说,每个目录都有 16190{1..7}.pdf


现在假设我想将所有(从所有提到的目录)移动161901.pdf到一个特定的目录(比如xyz),并重命名为它的父文件夹的 name.pdf。

解释 :-

这是所有列表161901.pdf

$ find -name 161901.pdf
./May-June-2011/161901.pdf
./Nov-Dec-2011/161901.pdf
./Summer-2012/161901.pdf
./Summer-2013/161901.pdf
./Summer-2014/161901.pdf
./Winter-2012/161901.pdf
./Winter-2013/161901.pdf
./Winter-2014/161901.pdf
Run Code Online (Sandbox Code Playgroud)

我希望./May-June-2011/161901.pdf应该xyz使用新名称May-June-2011.pdf(文件所在的目录名称)将其移入。即移动./May-June-2011/161901.pdf./xyz/May-June-2011.pdf

同样./Nov-Dec-2011/161901.pdf./xyz/Nov-Dec-2011.pdf./Summer-2012/161901.pdf./xyz/Summer-2012.pdf等(最高./Winter-2014/161901.pdf./xyz/Winter-2014.pdf)。

的预期输出ls xyz是:

$ls xyz
May-June-2011.pdf
Nov-Dec-2011.pdf
Summer-2012.pdf
Summer-2013.pdf
Summer-2014.pdf
Winter-2012.pdf
Winter-2013.pdf
Winter-2014.pdf
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?(如何find -exec或使用循环或其他方式)

Pan*_*dya 0

后来我发现 while read -r line非常有帮助,并且我通过以下命令成功了:-

find -name 161901.pdf | while read -r line; do mv $line ./xyz/$(echo $line | cut -d "/" -f 2).pdf; done
Run Code Online (Sandbox Code Playgroud)

解释:-

  • 这里find -name 161901.pdf列出了创建的文件(已经在问题中提到),这些文件通过管道while循环,而路径存储在变量中line
  • cut -d "/" -f 2过滤目录名称例如-May-June-2011
  • 最后mv $line ./xyz/$(echo $line | cut -d "/" -f 2).pdf移动文件(重命名为它们所在的目录名称)

所以,find+while循环mv使用cut命名完成了我想要的。