【问题标题】:renaming particular files in the subfolders with full directory path使用完整目录路径重命名子文件夹中的特定文件
【发布时间】:2021-05-08 21:44:18
【问题描述】:

专家,我有很多文件夹,文件夹内有很多子文件夹,子文件夹包含许多文件。但是,在所有子文件夹中,一个文件名相同,即 input.ps。现在我想要用完整路径和文件名重命名相同的 input.ps

所以所有目录下的input.ps都要重命名为home_wuan_data_filess_input.ps

我试过了

#!/bin/sh
for file in /home/wuan/data/filess/*.ps
do
mv $file $file_
done

但它并没有像我预期的那样做,我希望专家能帮助我。提前谢谢。

【问题讨论】:

    标签: linux bash for-loop find rename


    【解决方案1】:

    所以所有目录中的input.ps 应该重命名为home_wuan_data_filess_input.ps

    您可以使用这个find 解决方案:

    find /home/wuan/data/filess -type f -name 'input*.ps' -exec bash -c '
    for f; do fn="${f#/}"; echo mv "$f" "${fn//\//_}"; done' _ {} +
    

    【讨论】:

    • 请注意,echo 仅用于测试目的。一旦您对输出感到满意,只需在 mv 之前删除 echo
    • 我会测试并让你知道@anubhava
    • 不,它不起作用...实际上我的文件与 input_c1.ps、input_c4.ps、input_c2.ps 等略有不同...但它只提供了最后一个文件我做了 -type f -名称 'input.ps' 到 -type f -name 'input_b*.ps'
    • 是的,我刚刚更新了。我们只需要-name 'input*.ps'
    • 让我检查一下先生
    【解决方案2】:

    好的,所以file 最终会成为

    /home/wuan/data/filess/input.ps
    

    我们需要的是路径和完整的蛇形名称。让我们从获取路径开始:

    for f in /home/wuan/data/filess/*.ps; do
        path="${f%*/}";
    

    这将匹配f 的子字符串,直到最后一次出现/,有效地为我们提供了路径。

    接下来,我们要对所有东西进行snake_case,这更容易:

    for f in /home/wuan/data/filess/*.ps; do
        path="${f%*/}";
        newname="${f//\//_}"
    

    这会将/ 的所有实例替换为_,并给出您希望新文件具有的名称。现在让我们把所有这些放在一起,将文件f 移动到path/newname

    for f in /home/wuan/data/filess/*.ps; do
        path="${f%*/}";
        newname="${f//\//_}"
        mv "${f}" "${path}/${newname}"
    done
    

    这应该可以解决问题


    这是列出您可以使用的some of the bash string manipulations 的众多网站之一。

    抱歉更新延迟,我的大楼刚刚断电:)

    【讨论】:

      【解决方案3】:
      while read line;
      do 
         fil=${line//\//_};                             # Converts all / characters to _ to form the file name
         fil=${fil:1};                                  # Remove the first -                                 
         dir=${line%/*};                                # Extract the directory
         echo "mv $line $dir/$fil";                     # Echo the move command
         # mv "$line" "$dir/$fil";                      # Remove the comment to perform the actual command
      done <<< "$(find /path/to/dir -name "input.ps")"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 2021-06-21
        • 2016-12-11
        • 2015-10-26
        • 2011-04-13
        相关资源
        最近更新 更多