【问题标题】:How to replace substrings in a column of file with strings from another file using awk?如何使用awk将文件列中的子字符串替换为另一个文件中的字符串?
【发布时间】:2019-04-29 02:50:07
【问题描述】:

我有两个文件,想用 awk 将一列文件中的子字符串替换为另一个文件中的字符串

f1:
1a1 aaa 777
3_3 ccc 6b6
3.3 ddd 666

f2:
b5g9aaa8y
5_6ccc9.

output:
1a1 b5g9aaa8y 777
3_3 5_6ccc9. 6b6

我想我可以分两步完成:

  1. 制作子字符串和字符串的交集字典文件
  2. 使用 awk(sub) 来完成它

但是,是否有一行 awk 命令来检查字符串中是否存在子字符串,然后进行替换?

#

对不起,我应该解释得更清楚。

  1. file2 中的字符串格式和长度不固定。
  2. file1 和 file2 的记录数不同。 file2是file1的子集,只需要输出file2中的字符串
  3. 假设没有多次点击

【问题讨论】:

    标签: awk


    【解决方案1】:

    EDIT2:由于 OP 现在更改了示例并添加了完整的条件,因此添加了此解决方案。

    awk 'FNR==NR{a[$2]=$1;b[$2]=$3;next} {for(i in a){if(index($0,i)){print a[i],$0,b[i];delete a[i];break}}}'  Input_file1   Input_file2
    

    或者现在添加非单线形式的解决方案。

    awk '
    FNR==NR{
      a[$2]=$1
      b[$2]=$3
      next
    }
    {
      for(i in a){
        if(index($0,i)){
          print a[i],$0,b[i]
          delete a[i]
          break;
        }
      }
    }'  Input_file1  Input_file2
    


    编辑:根据@sjsam 的评论,substr 的情况范围可能会有所不同,然后根据示例提供,也可以尝试以下操作。它认为您只想将字母作为索引并从 Input_file2 行中删除所有内容(OP 也在 cmets 中确认了这一点)。

    awk 'FNR==NR{val=$0;gsub(/[^[a-zA-Z]]*/,"");a[$0]=val;next} {$2=$2 in a?a[$2]:$2} 1'  Input_file2   Input_file1
    


    请您尝试关注一下。

    awk 'FNR==NR{a[substr($0,3,3)]=$0;next} {$2=$2 in a?a[$2]:$2} 1' Input_file2   Input_file1
    

    输出如下。

    111 33aaa8 777
    333 56ccc9 666
    

    【讨论】:

      猜你喜欢
      • 2016-05-23
      • 2011-07-01
      • 2020-10-08
      • 2019-03-21
      • 1970-01-01
      • 2018-05-19
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      相关资源
      最近更新 更多