【问题标题】:merging multiple rows into one row per record seprated by a blank line in unix [closed]将多行合并为一行,每条记录由unix中的空行分隔[关闭]
【发布时间】:2021-07-04 02:24:39
【问题描述】:

我有一个文本文件,其中每条记录都以 no 和 name 开头,并以空行结尾。我想在一行中将每条记录作为逗号分隔值。我尝试了以下代码,其代码文件和文本文件链接附在下面: biosample.txt sark.awk

unix命令:运行代码是:

gawk -f sark.awk biosample.txt

然后运行:

sed 's/,,/\n/g' <biosample.txt > out.txt

out.txt 有点不一致/混乱/混乱。

我希望每条记录在一行中,只为以下标题提取值:

record name
Identifiers
Organism
strain
isolate
serovar
isolation source
collected by
collection date
geographic location
host
host disease
Accession
ID
potential_contaminant
sample type
Description

从每条记录中选取每个标题的值,并用新行分隔。

谢谢

【问题讨论】:

  • 您能否发布输入文件的摘录以及输出文件的外观?
  • edit您的问题,并在您的问题中直接显示代码和一个小输入文件,格式为代码块。 “discrepant/messy/confusing” 不是一个充分的问题描述。显示实际输出和预期输出,并在必要时解释实际输出错误的原因。
  • @user3506020 - sark.awk 的缩进很荒谬。
  • gawk 输入和sed 输入(后者必须是gawk 输出)怎么可能同名biosample.txt
  • 我已将我的文件和代码附在可下载的帖子中。

标签: unix awk sed


【解决方案1】:

这是awk 的简单实现:

BEGIN   { print "record name,Identifiers,Organism,strain,isolate,serovar,"\
                "isolation source,collected by,collection date,"\
                "geographic location,host,host disease,Accession,ID,"\
                "potential_contaminant,sample type,Description"
          RS="\r\n"
          ORS=""
        }
sub(/^[0-9]*: /,"")     { r[1] = $0; next }
sub(/^Identifiers: /,""){ r[2] = $0; next }
sub(/^Organism: /,"")   { r[3] = $0; next }
/^ /                    { split($0, a, "=") }
/^ *\/strain=/          { r[4] = a[2] }
/^ *\/isolate=/         { r[5] = a[2] }
/^ *\/serovar=/         { r[6] = a[2] }
/^ *\/isolation source=/{ r[7] = a[2] }
/^ *\/collected by=/    { r[8] = a[2] }
/^ *\/collection date=/ { r[9] = a[2] }
/^ *\/geographic locati/{ r[10] = a[2] }
/^ *\/host=/            { r[11] = a[2] }
/^ *\/host disease=/    { r[12] = a[2] }
/^Accession:/           { r[13] = $2; r[14] = $4 }
/^ *\/potential_contami/{ r[15] = a[2] }
/^ *\/sample type=/     { r[16] = a[2] }
/^Description:/         { getline; r[17] = $0 }
/^$/                    { if (r[1]) {   for (i = 1; i < 17; ++i) print r[i]","
                                        print r[i]"\n"
                                        delete r
                                    }
                        }

【讨论】:

  • 非常感谢,这真的很好用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2020-01-24
  • 1970-01-01
  • 2019-08-22
  • 2022-10-14
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多