bash - 在 bash 中重命名文件的陷阱

标签 bash posix renaming

我正在这里阅读指南 http://mywiki.wooledge.org/BashFAQ/030 在这个链接上给出了一些例子,我试图理解它们,一个示例代码说

# Bash
# Replace all spaces with underscores
for f in *\ *; do mv -- "$f" "${f// /_}"; done

到目前为止我所知道的是在搜索和替换时使用反斜杠来表示特殊字符,例如 ~ 或 # 等的空格 示例或在上面示例中的 shell 脚本中,它们有
使用过${f// /_}
正斜杠,我不清楚这是否允许?
在同一页面的另一个示例中 他们给出了一个删除空格并用下划线替换的示例

find . -depth -name "* *" -exec bash -c 'dir=${1%/*} base=${1##*/};<br/> mv "$1" "$dir/${base// /_}"' _ {} \;

在上面的例子中我不清楚以下内容
1) dir=${1%/*}
2) base=${1##*/}
3)当它说mv "$1"时上述语句中的 $1 是什么意思,
4) 最后 find 命令被 -exec <something> _ {} \; 关闭
现在下划线 _ 、大括号 {} 和反斜杠后跟\; 上面的冒号有什么用?
在第三个例子中,他们说

# tolower - convert file names to lower case
# POSIX
for file in "$@"do 
   [ -f "$file" ] || continue                # ignore non-existing names   
 newname=$(echo "$file" | tr '[:upper:]' '[:lower:]')     # lower case   
 [ "$file" = "$newname" ] && continue      # nothing to do   
 [ -f "$newname" ] && continue             # don't overwrite existing files  
  mv -- "$file" "$newname"done 

我不清楚以下几行
5)[ -f "$file" ] || continue # ignore non-existing names
我不清楚用 [ ] 测试条件如果 $file 存在那么 OR 条件有什么用 ||这里和 continue 语句
6)[ -f "$newname" ] && continue # don't overwrite existing files这里与第 5 点有同样的疑问

最佳答案

${f// /_}

表示:用下划线替换所有出现的空格

ref


${1%/*}

表示:删除/*的最短匹配从字符串末尾开始

ref


${1##*/}

表示:删除 */ 的最长匹配项从字符串前面开始

ref


when it says mv "$1" what is meant by $1

$1是第一个位置参数。所以如果你的脚本有这个

echo $1

你这样称呼

foo.sh 111

那么输出将是

111

finally the find command is being closed with -exec <something> _ {} \; now what is the use of an underscore _ , curly braces {} and a backslash followed by a colon above \;?

下划线是参数 $0 的占位符

ref

{} \;习语与 find 一起使用,也就是说:为每个文件运行此命令一次

ref


[ -f "$file" ] || continue

表示:如果 $file不是FILE,则继续(立即结束循环的当前迭代并开始下一个)

ref

关于bash - 在 bash 中重命名文件的陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15308513/

相关文章:

c - 在 c 中实现一个简单的 shell - wc 命令不起作用

bashrc 在更改目录时不导出函数中的变量

shell -/dev/null 2>&1 是什么?

python - 选择文件名的特定部分将其移动到开头

svn - TortoiseSVN 无法提交,说 "forbidden by server"

bash - 如何在 "bash -c"命令中使用位置参数?

linux - 如何清理 bash 中分隔符也在双引号内的 csv?

C++ : Interix signals

linux - 在 AWK 中可移植地处理任意参数

visual-studio - 重命名类文件不再提示重命名所有匹配项