【问题标题】:Editing every file in a directory after opening it bash打开目录后编辑目录中的每个文件bash
【发布时间】:2018-02-17 08:24:19
【问题描述】:

环顾四周,我没有看到我在寻找什么。一些类似的东西,但由于某种原因,我到目前为止尝试的方法没有奏效。

我的主要目标:

  1. 在我的当前目录中运行脚本
  2. 打开图片看看是什么
  3. 重命名刚刚查看的图片
  4. 重复该过程而不再次运行脚本

这些是我试图追踪的来源:

Bash Shell Loop Over Set of Files

Bash loop through directory and rename every file

How to do something to every file in a directory using bash?

================================================ ====================================

echo "Rename pictures. Path"
read path
for f in $path
do  
    eog $path
    echo "new name"
    read newname
    mv $path $newname
    cat $f
done

【问题讨论】:

  • 您是否尝试在eog 行之后添加&&eog $path &&
  • @JustinM.Keyes,这有什么好处?如果您想避免为eog 失败的文件运行其余的循环迭代,那么eog "$path" || continue 会做得更好(不仅跳过echo,还跳过read、@987654332 @ 和 cat)。

标签: linux bash scripting


【解决方案1】:

您应该向脚本传递一个参数,而不是尝试使其具有交互性。您还有许多报价问题。试试这样的东西(未经测试):

#!/usr/bin/env bash

moveFile() {
    local newName=
    until [[ $newName ]]; do
        printf '%s ' 'new name:'
        read -er newName # -e implies Bash with readline
        echo
    done
    mv -i "$1" "${1%/*}/${newName}"
}

if [[ ! -d $1 ]]; then
    echo 'Must specify a path' >&2
    exit 1
fi

for f in "$1"/*; do
    eog "$f"
    moveFile "$f"
done

【讨论】:

  • 当你在这里调用一个函数时,我的系统似乎忽略了它(简单的剪切和粘贴)我必须确保我做的任何事情才能使函数 moveFile() 被识别
  • @user1770303 我不这么认为。这里使用了一些 bashism,因此首先要确保您实际使用的是 bash(带有 #!/bin/bashshebang)。这个脚本当然假设您将目录作为 arg 传递。使用set -x 或运行bash -x scriptname 进行调试。您应该在输出中看到函数调用及其参数。 编辑 也看到我打错了...再次复制/粘贴:)
【解决方案2】:

你可能想尝试这样的事情:

for f in $*; do
    eog $f
    echo "new name:"
    read newname
    mv $f $newname
done

如果您将脚本命名为rename.sh,则可以调用

./rename.sh *gif

查看所有扩展名为“gif”的文件。

【讨论】:

  • for f in $*; do 非常错误——如果您运行yourscript "argument one" "argument two",它会将其视为"argument" "one" "argument" "two",在空格上拆分并丢失原始引用所暗示的边界。请改用for f in "$@"; do,或仅使用for f; do
【解决方案3】:

使用find命令可以递归搜索指定目录下的图片文件。

echo -n "Rename pictures. Input image directory: "
read path

for f in `find $path -type f`
do
    eog $f
    echo -n "Enter new name: "
    read newname
    mv $f $newname
    echo "Renamed $f to $newname."
done

【讨论】:

  • 参见BashPitfalls #1 -- 以这种方式迭代for 的输出是非常错误的,在带有空格的文件名或名称可以被解释为glob 的文件名上失败。此外,需要引用变量扩展("$f", "$newname"` 等)才能正确;见shellcheck.net
  • 另外,最好避免使用echo -n;请参阅the POSIX spec for echo,尤其是应用程序部分,建议改为printf
猜你喜欢
  • 2021-01-16
  • 2012-11-13
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
  • 2018-10-29
  • 2014-09-18
  • 1970-01-01
  • 2019-04-08
相关资源
最近更新 更多