Linux 连接实用程序提示输入文件未排序

标签 linux bash sorting join text-processing

我有两个文件:

file1 的格式为:

field1;field2;field3;field4

(file1 最初是未排序的)

file2 的格式为:

field1

(文件2已排序)

我运行以下 2 个命令:

sort -t\; -k1 file1 -o file1 # to sort file 1
join -t\; -1 1 -2 1 -o 1.1 1.2 1.3 1.4 file1 file2

我收到以下消息:

join: file1:27497: is not sorted: line_which_was_identified_as_out_of_order

为什么会这样?

(我还尝试对 file1 进行排序,考虑到整行,不仅是该行的第一个文件,但没有成功)

排序-t\; -c file1 不输出任何内容。在第 27497 行附近,情况确实很奇怪,这意味着排序没有正确完成它的工作:

              XYZ113017;...
line 27497--> XYZ11301;...
              XYZ11301;...

最佳答案

补充Wumpus Q. Wumbley's helpful answer具有更广阔的视角(因为我发现这篇文章研究的是一个稍微不同的问题)。

  • 使用join输入文件必须仅按连接字段排序,否则您可能会看到 OP 报告的警告。

有两种常见的情况,在对输入文件进行排序时,错误地包含了输入文件:

  • 如果您确实指定了一个字段,很容易忘记您还必须指定一个停止字段 - 即使您只定位 1 个字段 - 因为 sort如果仅指定了 start 字段,则使用该行的其余部分;例如:

    • sort -t, -k1 ... # !! FROM field 1 THROUGH THE REST OF THE LINE
    • sort -t, -k1,1 ... # Field 1 only
  • 如果您的排序字段是输入中的第一个字段可能根本不指定任何字段选择器

    • 但是,如果字段值可以是彼此的前缀子字符串,对整行进行排序将不会(必然)产生与仅按第一个字段排序相同的排序顺序:
    • sort ... # NOT always the same as 'sort -k1,1'! see below for example

陷阱示例:

#!/usr/bin/env bash

# Input data: fields separated by '^'.
# Note that, when properly sorting by field 1, the order should
# be "nameA" before "nameAA" (followed by "nameZ").
# Note how "nameA" is a substring of "nameAA".
read -r -d '' input <<EOF
nameA^other1
nameAA^other2
nameZ^other3
EOF

# NOTE: "WRONG" below refers to deviation from the expected outcome
#       of sorting by field 1 only, based on mistaken assumptions.
#       The commands do work correctly in a technical sense.

echo '--- just sort'
sort <<<"$input" | head -1 # WRONG: 'nameAA' comes first

echo '--- sort FROM field 1'
sort -t^ -k1 <<<"$input" | head -1 # WRONG: 'nameAA' comes first

echo '--- sort with field 1 ONLY'
sort -t^ -k1,1 <<<"$input" | head -1 # ok, 'nameA' comes first

解释:

  • 当不限制排序到第一个字段时,它是字符的相对排序顺序。 ^A (列索引 6)在这个例子中很重要。换句话说:字段分隔符与数据进行比较,这就是问题的根源:^具有比 A 更高的 ASCII 值,因此在 'A' 之后排序,导致以 nameAA^ 开头的行在带有 nameA^ 的那个之前排序.

  • 注意:问题有可能在一个平台上出现,但在另一个上被掩盖,这取决于语言环境和字符集设置和/或 sort使用的实现;例如,区域设置为 en_US.UTF-8实际上,用 ,作为分隔符和 -允许的内部字段:

    • sort用于 OSX 10.10.2( GNU sort 版本,5.93)排序 ,之前 - (符合ASCII值)
    • sort在 Ubuntu 14.04 (GNU sort 8.21) 上使用的相反:排序 -之前 , [1]

[1] 我不知道为什么 - 如果有人知道,请告诉我。用 sort <<<$'-\n,' 测试

关于Linux 连接实用程序提示输入文件未排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431673/

相关文章:

linux - 使用 AWK 或 SED 以及以下标签以逗号分隔

linux - 使用 expect 时收到垃圾字符

linux - 根据内容将文件分类到文件夹的 Bash 脚本;如何解决变量中的通配符?

arrays - 基本快速排序 : listing array with each partition call

c# - C# 数组中的 System.InvalidCastException 错误

linux - Kubernetes on Raspberry Pi kube flannel CrashLoopBackOff 和 kube dns rpc 错误代码 = 2

linux - 为什么 npm 不安装任何包?

linux - 如何从独立的 GNU screen session 中邮寄命令的输出?

perl - 你如何对 Data::Dumper 的输出进行排序?

php - CentOS安装php-mbstring报错