【问题标题】:Split .txt file into separate files taking name from one column and contents from another?将 .txt 文件拆分为单独的文件,名称来自一列,内容来自另一列?
【发布时间】:2020-08-23 13:35:21
【问题描述】:

如果有人问过这个问题,我深表歉意。我环顾四周,只能找到对我不起作用的类似问题。

我有一个制表符分隔的 .txt 文件,其中有两列我想拆分。我需要新文件的名称基于第一列,每个文件的内容作为第二列的内容。例如,我将拥有包含字符串word1Name1.txt,另一个名为Name2.txt 的文件包含word2 等等。我在 Ubuntu 18.04 上,希望从命令行完成。

Name1   word1
Name2   word2
Name3   word3

目前我已使用以下代码将 .txt 文件拆分为单独的文件:

split -1 largefile.txt

现在每个文件都是格式。使用字符串 I 希望成为首先出现的名称,然后是选项卡和所需的文件内容。

Name1   word1 

【问题讨论】:

  • 在这样的情况下,我们确实鼓励用户添加他们为解决自己的问题而付出的努力,所以请在您的问题中添加相同的内容,然后让我们知道。
  • 我明白了,我已经用我目前的内容编辑了这篇文章。

标签: ubuntu awk


【解决方案1】:

请您尝试关注一下。

awk '
{
  outfile=$1
  if(outfile!=prev){
    close(outfile)
  }
  print $2 > (outfile".txt")
  prev=$1
}
' Input_file

说明:添加详细说明。

awk '                           ##Starting awk program from here.
{
  outfile=$1                    ##Creating variable oufile which stores first field of current line.
  if(outfile!=prev){            ##Checking condition if outfile value is NOT equal to prev variable then do following.
    close(outfile)              ##Then closing outfile(output file) in backend, this step is to avoid error of too many opened files.
  }
  print $2 > (outfile".txt")    ##Printing current line 2nd field to outfile with .txt adding to it.
  prev=$1                       ##Creating variable prev which has 1st field value of current line.
}
' Input_file                    ##Mentioning Input_file name here.

【讨论】:

  • 这会正确拆分文件,但会在文件中留下成为名称的字符串。
  • @sjp,确定我现在只打印第二行。让我知道这现在是否可以正常工作?
【解决方案2】:

另一个 awk:

$ awk '{f=$1 ".txt";print $2 >> f;close(f)}' file

解释:

$ awk '{
    f=$1 ".txt"     # form the filename
    print $2 >> f   # append to file in case there are non-unique $1s
    close(f)        # close file to avoid running out of fds
}' file

【讨论】:

    猜你喜欢
    • 2021-03-13
    • 2023-03-31
    • 1970-01-01
    • 2013-08-30
    • 2014-04-10
    • 2022-01-21
    • 2013-04-13
    • 2021-12-03
    相关资源
    最近更新 更多