Bash 将文件移动到同名文件夹 [英] Bash move file to folder of same name

查看:78
本文介绍了Bash 将文件移动到同名文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在错误的位置发布这个,我提前道歉,我对脚本很陌生,更不用说stackoverflow了:

I apologize in advance if I am posting this in the wrong location, I am very new to scripting let alone stackoverflow:

我有许多以 .conf 结尾的文件,与许多同名但没有 .conf 扩展名的文件夹位于同一目录中.例如,我的目录如下所示:

I have a number of files ending in .conf in the same directory as a number of folders with the same names without the .conf extension. For example, my directory looks like this:

136
136.conf
139
139.conf
...

我想通过循环将 .conf 文件移动到相应的文件夹中.我以为我可以这样做:

I would like to move the .conf files into their corresponding folder with a loop. I thought I could do this:

for f in *.conf; do
    dir=${f:0:13}
    mv "$f" "$dir"
done

但我显然做错了什么.我将不胜感激任何人的帮助.

but I am obviously doing something incorrectly. I would greatly appreciate anyone's help with this.

推荐答案

使用 Bash 参数扩展通过删除扩展名(. 之后的任何内容)来派生目录名称:

Use Bash parameter expansion to derive the directory name by removing the extension (anything that follows the .):

for f in *.conf; do
  [[ -f "$f" ]] || continue # skip if not regular file
  dir="${f%.*}"
  mv "$f" "$dir"
done

这比子串方法好一点,因为我们不对文件名或目录名的长度做任何假设.

This is a little better than the substring approach since we make no assumption on the length of the filename or directory name.

这篇关于Bash 将文件移动到同名文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆