Saturday, January 27, 2024

[SOLVED] using bash, create files based on pattern match

Issue

we have a file with content as below.

/* ----------------- pattern_1 ----------------- */ 

jb: pattern_1  
Data:
asdflj 
adfas
Log: dir/log1

/* ----------------- pattern_2 ----------------- */ 

jb: pattern_2   typ: CM
comm: ${dir}/DISPV
mach: au_buh
description: "run flag"


/* ----------------- pattern_3 ----------------- */ 

jb: pattern_3   typ: fw 
own: buh
out_file: "${log}/jl.log"
err: "log.err"

the file has to be split into 3 and create as 3 separate files as below:

pattern_1.txt

/* ----------------- pattern_1 ----------------- */ 

jb: pattern_1  
Data:
asdflj 
adfas
Log: dir/log1

pattern_2.txt

* ----------------- pattern_2 ----------------- */ 

jb: pattern_2   typ: CM
comm: ${dir}/DISPV
mach: au_buh
description: "run flag"

pattern_3.txt

/* ----------------- pattern_3 ----------------- */ 

jb: pattern_3   typ: fw 
own: buh
out_file: "${log}/jl.log"
err: "log.err"

tried "awk pattern matching", didn't work out. any help ??


Solution

Keeping these pattern comments in file:

awk '/\/\* -{17} [a-z0-9_]+ -{17} \*\// {if (x) close(x); split($0,a," "); if (a[3] != "") {x=a[3]".txt"} else {next}} {if (x) print > x}' file

This is an approximation where you need to have always the symbol - 17 times like you main file, and awk will search this string to know when to start and cut the content. Therefore it will provide a txt file for each pattern section of main file.



Answered By - mrexojo
Answer Checked By - Robin (WPSolving Admin)