【问题标题】:Create files of matching pattern from a single data file从单个数据文件创建匹配模式的文件
【发布时间】:2017-06-23 05:35:02
【问题描述】:

我有一个数据类型(file.dat)的文件,其中包含 ASCII 数据,包含两列。此文件也根据第一列排序。我想在 shell 或 awk 中编写一个脚本,以便为该排序文件中的类似记录创建新文件。假设我的文件由(四条记录)组成,如下所示...

100.00 321342
100.00 434243
100.00 543231
100.50 743893

因此,根据我的问题,这里应该创建两个文件。根据第一列的数据,一个文件由前三条记录组成,另一个文件由最后一条记录组成。

文件 1 包含

100.00 321342
100.00 434243
100.00 543231

文件 2 包含

100.50 743893

【问题讨论】:

  • 你有什么尝试吗?
  • 是的,我已经尝试过awk '{print >> $1; close($1)}' inputfile,但是它将列值作为创建文件的名称,而不是我想要 Timestep_column_value。例如对于上述输入数据文件(通过执行上述 awk 脚本)创建为 100.00 和 100.50,但我希望文件名应为 Timestep_100.00
  • 在这种情况下:awk '{print >> Timestep_$1; close($1)}' inputfile
  • @Chris Maes,你应该写下你的评论作为答案,但它必须是awk '{print >> "Timestep_"$1; close($1)}' inputfile,注意"Timestep_" 周围的双引号,否则它会被忽略并根据当前内容和 Sachin shinde 的评论输出到 100.00100.50,而不是 Timestep_100.00Timestep_100.50

标签: shell file awk


【解决方案1】:

您的文件

100.00 321342  
100.00 434243  
100.00 543231  
100.50 743893   

你需要什么

perl -a -nE 'qx( echo "$F[0] $F[1]" >> "Timestep_$F[0]" )' file

output 只是创建两个文件,一个的名称是 Timestep_100.00,另一个的名称是 Timestep_100.50,所以它是分开的按第一个唯一列的名称。而已。

$ cat Timestep_100.00   
100.00 321342  
100.00 434243  
100.00 543231    

和其他文件

$ cat Timestep_100.50   
100.50 743893  

【讨论】:

  • @user3439894 他/她从未在其问题中提及这一点
【解决方案2】:

这个脚本应该可以完成工作:

#!/bin/sh

exec 0<file.txt

makeit=yes
while read stp num; do
  if [ -f "Timestep_$stp" ]; then
    echo "File Timestep_$stp exists, exiting."
    makeit=no
    break
  fi
done


if [ $makeit = yes ]; then
  exec 0<file.txt
  while read stp num; do
    echo "$stp $num" >> Timestep_$stp
  done
  echo "Processing done."
fi

第一个循环检查文件不存在,否则结果会出错。

【讨论】:

    猜你喜欢
    • 2020-12-08
    • 2020-09-04
    • 2016-08-18
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多