【问题标题】:Replace a word using different files Bash使用不同的文件替换一个单词 Bash
【发布时间】:2020-10-01 08:52:03
【问题描述】:

我想编辑我的 1.txt 文件,找到一个单词并将其替换为 2.txt 中的对应单词,并添加文件 2 的其余字符串。

我有兴趣维护我的 1.txt 文件的顺序。

>title1
ID1 .... rest of string im not interested
>title2
ID2 .... rest of string im not interested
>title3
ID3 .... rest of string im not interested
>title....

但我想添加我的文件2的信息

>ID1  text i want to extract
>ID2  text i want to extract
>ID3  text i want to extract
>IDs....

最后我想用这个结构创建一个新文件

>title1
ID1 .... text I want
>title2
ID2 .... text I want
>title3
ID3 .... text I want
>title....

我尝试了几个 sed 命令,但大多数都没有完全替换 ID# 那是在两个文件中。希望它可以在 bash 中完成

感谢您的帮助

尝试失败.. 我的代码是 文件 1 = cog_anotations.txt,文件 2=Real.cog.txt ID= COG05764、COG 015668 等...

sed -e '/COG/{r Real.cog.txt' -e 'd}' cog_anotations.txt
sed "s/^.*COG.*$/$(cat Real.cog.txt)/" cog_anotations.txt
sed -e '/\$COG\$/{r Real.cog.txt'  -e 'd}' cog_anotations.txt
grep -F -f cog_anotations.txt Real.cog.txt > newfile.txt
grep -F -f Real.cog.txt cog_anotations.txt > newfile.txt

【问题讨论】:

  • 向我们展示您的失败尝试

标签: bash sed replace find


【解决方案1】:

文件.awk:

BEGIN { RS=">" }
{ 
  if (FILENAME == "1.txt") {
    a[$2]=$1; b[$2]=$2; 
  } 
  else { 
      if ($1 == b[$1]) {
        if ($1 !="") { printf(">%s\n%s",a[$1],$0) } 
      }
  }
}

呼叫:

gawk -f file.awk 1.txt 2.txt

文件的顺序很重要。

结果:

>title1
ID1  text i want to extract
>title2
ID2  text i want to extract
>title3
ID3  text i want to extract

解释:

第一个文件在“>”处被划分为记录,然后创建了两个关联数组。仅对第二个文件执行 else 正文。接下来我们检查第二个文件的字段 1 是否在表 b 中,如果是,则格式化并打印下一行。

【讨论】:

    【解决方案2】:

    不要写一些嵌套的 grep。
    带有查找表的简单的一次性逻辑:

    declare -A lookup
    while read key txt
    do lookup["$key"]="$txt"
    done < 2.txt
    
    while read key txt
    do echo "${lookup[$key]:-$txt}"
    done < 1.txt
    

    【讨论】:

      猜你喜欢
      • 2015-03-02
      • 1970-01-01
      • 2017-11-04
      • 2012-02-26
      • 2016-08-19
      • 2019-06-24
      • 1970-01-01
      • 2022-01-18
      • 2016-06-11
      相关资源
      最近更新 更多