split the content of the file based on the delimiter not per line using awk, grep or sed

StackOverflow https://stackoverflow.com/questions/23468209

  •  15-07-2023
  •  | 
  •  

Question

Assuming I have a file that contains this:


! 
Title1 
     Data1 
! 
Title2
    Data1
    Data2
    Data3 
! 
Title3
    Data1
    Data2
    Data3 
! 
end 
!

I want to split the contents of the file and use (!) punctuation mark as the delimiter. Using awk I think is a bad idea because based on my observation it parses the file line by line, which is not what I need. Please help. Thanks

Was it helpful?

Solution

awk works fine with ! as separator.

awk -vRS="[!]" 'NR==3' file

Title2
    Data1
    Data2
    Data3

Here it prints record number 3 and as you see its not a single line.

OTHER TIPS

I think you stand a better chance with awk than with either sed or grep. For example, if your data is in a file called data, then this:

awk 'BEGIN{RS="!"} {print "[[" $0 "]]"}' data

produces:

[[]]
[[ 
Title1 
     Data1 
]]
[[ 
Title2
    Data1
    Data2
    Data3 
]]
[[ 
Title3
    Data1
    Data2
    Data3 
]]
[[ 
end 
]]
[[
]]

The only parts to quibble about are the empty record before the first delimiter and the record consisting of just a newline after the last delimiter. It wouldn't be hard to eliminate those two records.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top