【问题标题】:select and process columns of text csv选择和处理文本 csv 的列
【发布时间】:2021-07-21 08:43:14
【问题描述】:

我有一个类似的 csv 文本文件

2008-01-14T13:38:37.000,10.36,92.7,43.9,C200801141338s,20080114T133837M583Z044
2008-01-16T11:54:44.100,32.35,85.29,12.0,C200801161154d,20080116T115444M589Z012
...

用awk '{print $1,$5,$6} 输出第一列(日期时间)和最后两列很容易,但我想重新格式化日期时间,比如2008-01-14T13:38:37.000 到20080114_133837.x。怎么做?谢谢。

【问题讨论】:

  • Real CSV 实际上是一种相当复杂的格式。如果这是任何一种重要的应用程序,您应该使用一个好的 CSV 库。我知道 perl 和 python 都有。

标签: bash awk text sed


【解决方案1】:

仅使用您展示的示例,请您尝试以下操作。

awk '
BEGIN{
  FS=OFS=","
}
{
  gsub(/-|:/,"",$1)
  sub(/T/,"_",$1)
  sub(/\.[0-9]+$/,".x",$1)
  print $1,$5,$6
}
' Input_file

说明:为上述添加详细说明。

awk '                        ##Starting awk program from here.
BEGIN{                       ##Starting BEGIN section of this program from here.
  FS=OFS=","                 ##Setting FS, OFS as comma here.
}
{
  gsub(/-|:/,"",$1)          ##Globally substituting - OR : with NULL in $1.
  sub(/T/,"_",$1)            ##Substituting T with _ here in $1.
  sub(/\.[0-9]+$/,".x",$1)   ##Substituting .[0-9]+$ at last of 1st field with .x
  print $1,$5,$6             ##Printing 1st, 5th and 6th fields here.
}
' Input_file                 ##Mentioning Input_file name here.

【讨论】:

    【解决方案2】:

    另一种选择是进行拆分 + 连接并一步完成:

    awk '
    BEGIN{ FS=OFS="," }
    split($1, a, /[-:.T]+/) >= 6 {
       print a[1] a[2] a[3] "_" a[4] a[5] a[6] ".x", $5, $6
    }' file
    
    20080114_133837.x,C200801141338s,20080114T133837M583Z044
    20080116_115444.x,C200801161154d,20080116T115444M589Z012
    

    【讨论】:

    • 嗨@anubhava,>= 6是什么意思?
    • >=6 也可以跳过。它只是确保 split 函数在数组 a 中返回至少 6 个项目
    猜你喜欢
    • 2014-02-15
    • 2018-12-05
    • 2015-09-13
    • 2019-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    相关资源
    最近更新 更多