根据另一个文件内容中的完全匹配重命名文件名的一部分 [英] Rename part of file name based on exact match in contents of another file
问题描述
我想重命名一堆文件,方法是仅更改文件名的一部分,然后根据另一个文件列表中的完全匹配项进行更改.例如,如果我有以下文件名:
I would like to rename a bunch of files by changing only one part of the file name and doing that based on an exact match in a list in another file. For example, if I have these file names:
sample_ACGTA.txt
sample_ACGTA.fq.abc
sample_ACGT.txt
sample_TTTTTC.tsv
sample_ACCCGGG.fq
sample_ACCCGGG.txt
otherfile.txt
,我想根据这些完全匹配找到并替换,这些完全匹配在另一个名为replaces.txt的文件中找到:
and I want to find and replace based on these exact matches, which are found in another file called replacements.txt:
ACGT name1
TTTTTC longername12
ACCCGGG nam7
ACGTA another4
以使所需的结果文件名为
So that the desired resulting file names would be
sample_another4.txt
sample_another4.fq.abc
sample_name1.txt
sample_longername12.tsv
sample_nam7.fq
sample_nam7.txt
otherfile.txt
我不想更改内容.到目前为止,我已经根据我在此网站上的搜索结果尝试了sed
和mv
.使用sed
,我了解了如何使用列表替换文件的内容:
I do not want to change the contents. So far I have tried sed
and mv
based on my search results on this website. With sed
I found out how to replace the contents of the file using my list:
while read from to; do
sed -i "s/$from/$to/" infile ;
done < replacements.txt,
和mv
我找到了一种方法,如果有一个简单的替换方法,就可以重命名文件:
and with mv
I have found a way to rename files if there is one simple replacement:
for files in sample_*; do
mv "$files" "${files/ACGTA/another4}"
done
但是我怎样才能把它们放在一起做我想做的事?
But how can I put them together to do what I would like?
谢谢您的帮助!
推荐答案
您可以完美地组合for
和while
循环以仅使用mv
:
You can perfectly combine your for
and while
loops to only use mv
:
while read from to ; do
for i in test* ; do
if [ "$i" != "${i/$from/$to}" ] ; then
mv $i ${i/$from/$to}
fi
done
done < replacements.txt
使用sed
的替代解决方案可能包括使用执行替换结果的e
命令(请谨慎使用!请尝试在不使用e
结尾的情况下先打印将执行的命令).
An alternative solution with sed
could consist in using the e
command that executes the result of a substitution (Use with caution! Try without the ending e
first to print what commands would be executed).
因此:
sed 's/\(\w\+\)\s\+\(\w\+\)/mv sample_\1\.txt sample_\2\.txt/e' replacements.txt
将解析您的replaces.txt文件,并根据需要重命名所有.txt文件.
would parse your replacements.txt file and rename all your .txt files as desired.
我们只需要添加一个循环来处理其他扩展:
We just have to add a loop to deal with the other extentions:
for j in .txt .bak .tsv .fq .fq.abc ; do
sed "s/\(\w\+\)\s\+\(\w\+\)/mv 'sample_\1$j' 'sample_\2$j'/e" replacements.txt
done
(请注意,当它尝试重命名不存在的文件时(例如,当它尝试执行mv sample_ACGT.fq sample_name1.fq
但文件sample_ACGT.fq
不存在时,您应该会收到错误消息)
(Note that you should get error messages when it tries to rename non-existing files, for example when it tries to execute mv sample_ACGT.fq sample_name1.fq
but file sample_ACGT.fq
does not exist)
这篇关于根据另一个文件内容中的完全匹配重命名文件名的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!