awk:当记录中的第一个字段相同时,并排打印行

awk:当记录中的第一个字段相同时,并排打印行,awk,append,Awk,Append,我有一个包含如下行的文件 a x1 b x1 q xq c x1 b x2 c x2 n xn c x3 我想在每一行的第一个字段上进行测试,如果有匹配项,我想将匹配的行附加到第一行。输出应该如下所示 a x1 b x1 b x2 q xq c x1 c x2 c x3 n xn 使用awk您可以做到以下几点,我们将非常感谢您提供的任何帮助: awk '{arr[$1]=arr[$1]?arr[$1] " " $0:$0} END {for (i in arr) print arr[i]}'

我有一个包含如下行的文件

a x1
b x1
q xq
c x1
b x2
c x2
n xn
c x3
我想在每一行的第一个字段上进行测试,如果有匹配项,我想将匹配的行附加到第一行。输出应该如下所示

a x1
b x1 b x2
q xq
c x1 c x2 c x3
n xn

使用
awk
您可以做到以下几点,我们将非常感谢您提供的任何帮助:

awk '{arr[$1]=arr[$1]?arr[$1] " " $0:$0} END {for (i in arr) print arr[i]}' file
n xn
a x1
b x1 b x2
c x1 c x2 c x3
q xq

要保留输入顺序,请执行以下操作:

$ awk '
{
    if ($1 in vals) {
        prev = vals[$1] " "
    }
    else {
        prev = ""
        keys[++k] = $1
    }
    vals[$1] = prev $0
}
END {
    for (k=1;k in keys;k++)
        print vals[keys[k]] 
}
' file
a x1
b x1 b x2
q xq
c x1 c x2 c x3
n xn
我最后做的事。(埃德·莫顿和琼特的回答显然更加优雅。)

首先,我将输入文件的第一列保存在一个单独的文件中

awk '{print $1}' input.file.txt > tmp0
然后用行保存输入文件,删除$1字段中的重复值

awk 'BEGIN { FS = "\t" }; !x[$1]++ { print $0}' input_file.txt > tmp1 
然后用重复的$1字段保存所有行

awk 'BEGIN { FS = "\t" }; x[$1]++ { print $0}' input_file.txt >tmp2 
然后保存非重复文件(tmp1)的$1字段

我使用for循环将重复文件(tmp2)和删除的重复文件(tmp1)中的行拉入到输出文件中

for i in $(cat tmp3)
do
if [ $(grep -w $i tmp0 | wc -l) = 1 ] #test for single instance in the 1st col of input file
then
echo "$(grep -w $i tmp1)" >> output.txt #if single then pull that record from no dupes
else
echo -e "$(grep -w $i tmp1) \t $(grep -w $i tmp2 | awk '{ 
            printf $0"\t" }; END { printf "\n" }')"   >> output.txt # if not single then pull that record from no_dupes first then all the records from dupes in a single line.
fi
done
最后删除tmp文件

rm tmp* # remove all the tmp files

这将在某些AWK(OSX?)上产生语法错误,因为三元运算符周围缺少括号
arr[$1]=arr[$1]?arr[$1]“”“$0:$code>应该写入
arr[$1]=(arr[$1]?arr[$1]“”“$0:$0:
或者更好的方法是删除两次指定$0的冗余:
arr[$1]=(arr[$1]?arr[$1]:”)$0
这是很久以前的事了!今天看到了,谢谢你的回复-以及格式良好的代码-希望其他人会觉得有用。对我来说,我正在做的项目是时间敏感的,我必须在有限的理解力下进行变通。以下是我最后做的:-
rm tmp* # remove all the tmp files