【问题标题】:Use regular expression in for loop to copy files在for循环中使用正则表达式复制文件
【发布时间】:2021-12-24 03:46:22
【问题描述】:

我有一个包含部分文件名列表的 txt 文件。我只想将 txt 文件中的那些文件复制到另一个目录。但是,我需要使用正则表达式来查找文件。我似乎无法让它正常工作。有什么建议吗?

$ cat file-names.txt

name1    ACTGC
name2    ACTGG
name3    AACTN

$ ls raw/

name1_R1.fastq.gz
name1_R2.txt
name2_R1.fastq.gz
name2_R2.txt
name3_R1.fastq.gz
name4_R2.txt
name5_R1.fastq.gz

$ for i in `cut -f1 file-names.txt` ; do cp raw/"$i"_*.gz ./ ; done

不幸的是,这给出了一个错误:

cp: raw/name1_*.gz: No such file or directory
cp: raw/name2_*.gz: No such file or directory
cp: raw/name3_*.gz: No such file or directory

如何让cprsync 识别* 通配符,而不是将其视为文字文件名?

感谢您的帮助。

【问题讨论】:

  • 你在这里使用 glob,而不是正则表达式。
  • 我无法重现这一点。这是我尝试过的:printf '%s\t%s\n' name1 ACTGC name2 ACTGG name3 AACTN > file-names.txt 创建文本文件,mkdir -p raw && touch raw/{name1_R1.fastq.gz,name1_R2.txt,name2_R1.fastq.gz,name2_R2.txt,name3_R1.fastq.gz,name4_R2.txt,name5_R1.fastq.gz} 创建各种文件,然后像您一样使用for i in `cut -f1 file-names.txt` ; do cp raw/"$i"_*.gz ./ ; done。它按预期工作。您能否在不重复使用任何现有文件的情况下在新目录中重试,看看问题是否仍然存在?

标签: bash macos for-loop cp


【解决方案1】:

给定:

$ ls -1 name{1..5}*
name1_R1.fastq.gz
name1_R2.txt
name2_R1.fastq.gz
name2_R2.txt
name3_R1.fastq.gz
name4_R2.txt
name5_R1.fastq.gz

你可以这样做:

while read -r fn _; do    # no need for cut - shell can split
    ls -1 "${fn}_"*".gz"  # concatenate and expand this way
                          # "$fn"_*.gz works too
    # change to your cp as desired...
done <file-names.txt      # while loop best to loop over file in shell

列表:

name1_R1.fastq.gz
name2_R1.fastq.gz
name3_R1.fastq.gz

顺便说一句:

for i in `cut -f1 file-names.txt` ; do ls "$i"_*.gz ; done

在我的电脑上工作。不知道为什么它不在您的计算机上?

【讨论】:

  • OP 的尝试有什么问题?
  • 自测试以来,我删除了评论。 (如果* 在变量或引用字符串中,您确实需要评估...)他的代码实际上可以在我的计算机上运行,​​所以我不能说为什么它对他不起作用。
  • 他的脚本中可能有set -o noglob
猜你喜欢
  • 1970-01-01
  • 2016-03-20
  • 2014-01-19
  • 2021-05-15
  • 2023-02-21
  • 1970-01-01
  • 2019-05-25
  • 2014-02-24
  • 2014-04-12
相关资源
最近更新 更多