英文:
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='\t' read orig new; do
origfile="$orig"
newfile="$new"
rename -n -v "s/$origfile/$newfile/" *.txt
done < 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='\t' read -u3 orig new; do
for f in "$orig"_*.txt; do
mv -i -- "$f" "${new}${f:${#orig}}"
done
done 3< 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 "/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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论