【问题标题】:Joining multiple text fields and keeping everything..加入多个文本字段并保留所有内容..
【发布时间】:2018-03-10 15:30:32
【问题描述】:

我有大约十几个文件格式如下:

file1:
david@example.com:DSL
jacob@example.com:FIOS
stephen@example.com:DSL

file2: 
david@example.com:webspace
jacob@example.com:webspace
randy@example.com:webspace

file3:
david@example.com:www
randy@example.com:android

我希望他们最终能像这样

david@example.com:DSL:webspace:www
jacob@example.com:FIOS:webspace
stephen@example.com:DSL
randy@example.com:webspace:android

我在 shell 脚本文本处理方面相当薄弱,所以我一直在玩 GNU join -a 的各种链式和迭代排列,但没有得到所有东西。我不在乎数据是否在第一个字段上保持排序,但我希望其他字段的顺序保持不变;如果先遇到,应该先起来。

【问题讨论】:

  • 这不是免费的代码编写服务。自己尝试并发布代码,包括期望的和当前的行为。
  • @JimTuck 只是发布一些尝试,这就是我们所要求的:)

标签: linux bash join awk


【解决方案1】:

join生成三个或更多文件的外连接并不容易。 尝试类似:

#!/bin/bash

declare -A hash             # use the variable hash as an associative array
IFS=:                       # set the delimiter to ":"

for file in $@; do          # loop over the specified files
    while read line || [ -n "${line}" ]; do
        set -- $line        # split the line with ":"
        hash[$1]+=":$2"     # append the 2nd field to a hash keyed by the 1st field
    done < $file
done

for key in ${!hash[@]}; do  # loop over the hash keys
    echo "${key}${hash[$key]}"
done

用法是将上面的代码保存为脚本并说:./thisscript file1 file2 file3 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-11
    • 2012-08-10
    • 2017-11-24
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多