bash - 格式化文件内容
问题描述
我必须格式化我的文件的内容。这样如果我传入 .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; }}'
解决方案
您能否尝试以下操作(使用提供的样本进行测试)。
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.
推荐阅读
- asp.net-mvc - ASP.NET Web API 项目模板如何使用这个 HelpPage 区域,就像它不是一个区域一样?
- python - Python 正则表达式不会在 header.py 中引发异常
- python - 使用 Docker Python SDK 使容器保持活力
- .net - MsiInstallProduct 在窗口 2016 上抛出 NullReferenceException
- c++ - 声明一个 STL 容器来存储一个模板类型的变量
- r - R - 结合 ifelse 和 substr
- css - REACTJS - 3 个大小为 16:9 的基于网格的框,显示图片失真
- android - 如何使用 Dagger2 将 ViewModel 注入 BottomSheetDialogFragment?
- reactjs - antd UI Toolkit中Tabs组件中的TextArea和文本未呈现
- javascript - 删除使用 div 创建的表中的单行