根据另一个文件内容的完全匹配重命名文件名的一部分 [英] Rename part of file name based on exact match in contents of another file

查看:27
本文介绍了根据另一个文件内容的完全匹配重命名文件名的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过仅更改文件名的一部分并根据另一个文件中列表中的完全匹配来重命名一堆文件.例如,如果我有这些文件名:

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

我想根据这些完全匹配来查找和替换,它们可以在另一个名为 replacements.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

我不想更改内容.到目前为止,我已经根据我在这个网站上的搜索结果尝试了 sedmv.使用 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?

感谢您的帮助!

推荐答案

你可以完美地结合你的 forwhile 循环只使用 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

将解析您的 replacements.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆