使用查找表循环重命名文件,使用 ‘rename’ 命令。

huangapple go评论51阅读模式
英文:

Loop rename files using lookup table, with 'rename' command

问题

以下是翻译好的部分:

while IFS='\t' read orig new; do
        origfile="$orig"
        newfile="$new"
        rename -n -v "s/$origfile/$newfile/" *.txt
done < rename.tsv

请注意,代码部分已被保持原样,不进行翻译。

英文:

I'm trying to use a lookup table to rename files in a batch using a while loop.

Here are my filenames:

file1_a.txt
file2_a.txt
file3_b.txt
file4_b.txt
file5_c.txt

I also have a lookup table, tab-separated (rename.tsv). The first 1st column is the original string, and the 2nd column is the new string.

file1  file10
file2  file20
file3  file3
file4  file4

The expected output should be changing all the filenames as follows:

file10_a.txt
file20_a.txt
file3_b.txt
file4_b.txt
file5_c.txt

Here's my bash script. I'm using 'rename' and not 'mv' to make use of regex.

while IFS=&#39;\t&#39; read orig new; do
        origfile=&quot;$orig&quot;
        newfile=&quot;$new&quot;
        rename -n -v &quot;s/$origfile/$newfile/&quot; *.txt
done &lt; rename.tsv

This script produces no output, but also no errors, so it's not clear what I'm doing wrong. Any help is appreciated.

答案1

得分: 1

你也可以使用参数扩展方法和 mv

shopt -s nullglob

while IFS=$'\t' read -u3 orig new; do
    for f in "$orig"_*.txt; do
        mv -i -- "$f" "${new}${f:${#orig}}"
    done
done 3< rename.tsv

mv 可能会在出现错误时产生错误消息。

请参考Bash手册以获取文档。

英文:

You can also use parameter expansion methods and mv:

shopt -s nullglob

while IFS=&#39;\t&#39; read -u3 orig new; do
	for f in &quot;$orig&quot;_*.txt; do
		mv -i -- &quot;$f&quot; &quot;${new}${f:${#orig}}&quot;
	done
done 3&lt; rename.tsv

mv is likely to produce an error message on an error.

Refer to the Bash Manual for documentation.

答案2

得分: 1

If your rename command is not perl based, it doesn't support "/org/new/" syntax, which is a perl expression. Please try instead:

while IFS=$'\t' read -r orig new; do
    rename -v "$orig" "$new" *.txt
done < rename.tsv

Please note the usage of $'\t', not '\t'.
As a side note, your redundant variable assignments seem unnecessary.

英文:

If your rename command is not perl based, it doesn't support &quot;/org/new/&quot; syntax, which is a perl expression. Please try instead:

while IFS=$&#39;\t&#39; read -r orig new; do
    rename -v &quot;$orig&quot; &quot;$new&quot; *.txt
done &lt; rename.tsv

Please note the usage of $&#39;\t&#39;, not &#39;\t&#39;.
As a side note, your redundant variable assignments seem unnecessary.

huangapple
  • 本文由 发表于 2023年2月8日 12:48:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381477.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定