首页 > 解决方案 > 格式化文件内容

问题描述

我必须格式化我的文件的内容。这样如果我传入 .csv 文件第一列 - [SUCCESS]/[FAILURE],第二列 - *co.com,第三列 - 内容只想将内容保留在一行中,并添加逗号,如下所示

[SUCCESS] abc.co.com
This is 1st content,,,,/
asdfmmmm

[SUCCESS] abcdd.co.com
This is 2nd content
cabjdhds

[SUCCESS] abcasd.co.com
This is 3rd content...?/
cajbhjwd b

[FAILURE] ab.co.com
This is 3rd content...?/
cajbhjwd b

预期产出

[SUCCESS], abc.co.com, This is 1st content,,,,/ asdfmmmm............

[SUCCESS], abcdd.co.com, This is 2nd content cabjdhds..........

[SUCCESS], abcasd.co.com, This is 3rd content...?/ cajbhjwd b.........

[FAILURE], ab.co.com, This is 3rd content...?/ cajbhjwd b

在下面尝试过,但这会打印在一行中

cat file |awk 'BEGIN {accum_line = "";} /^[[a-z]+]/{if(length(accum_line)){print accum_line; accum_line = "";}} {accum_line = accum_line " ," $0;} END {if(length(accum_line)){print accum_line; }}' 

标签: bashawk

解决方案


您能否尝试以下操作(使用提供的样本进行测试)。

awk '
BEGIN{
  OFS=", "
}
/^\[/{
  $1=$1
  $0=$0","
  if(val){
    sub(/, $/,"",val)
    print val}
    val=""
  }
{
  val=(val?!/^\[/?val " ":val:"")$0
}
END{
  if(val){
    sub(/, $/,"",val)
    print val
  }
}
'  Input_file

说明:现在添加上面的说明。

awk '                                   ##Starting awk program here.
BEGIN{                                  ##Starting BEGIN section of this code here.
  OFS=", "                              ##Setting OFS as ", " for all lines here.
}                                       ##Closing BEGIN block here.
/^\[/{                                  ##Checking condition ig a line starts from [ then do following.
  $1=$1                                 ##Resetting $1 to value $1 to make OFS value in affect here.
  $0=$0","                              ##Concatenating , in current line.
  if(val){                              ##Checking if variable val is NOT NULL then do following.
    sub(/, $/,"",val)                   ##Substituting , and space at last of line with NULL in variable val.
    print val}                          ##Printing variable val here.
    val=""                              ##Nullifying variable val here.
  }
{
  val=(val?!/^\[/?val " ":val:"")$0     ##Creating variable val and concatenating its value with its own previous value along with space if line DO NOT start from [.
}
END{                                    ##Starting END block of this awk code now.
  if(val){                              ##Checking if val is present then do following.
    sub(/, $/,"",val)                   ##Substituting , and space at last of line with NULL in variable val.
    print val                           ##Printing variable val here.
  }
}
'  Input_file                           ##Mentioning Input_file name here.

推荐阅读