Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert newline before/after match for TSV

I'm going grey trying to figure out how to accomplish some regex matching to insert new lines. Example input/output below...

Example TSV Data:

Name    Monitoring  Tags
i-RBwPyvq8wPbUhn495 enabled "some:tags:with:colons=some:value:with:colons-and-dashes/and/slashes/yay606-values-001  some:other:tag:with-colons-and-hypens=MACHINE NAME  Name=NAMETAG    backup=true"
i-sMEwh2MXj3q47yWWP enabled "description=RANDOM BUSINESS INT01  backup=true Name=SOMENAME"

Desired Output:

Name    Monitoring  Tags
i-RBwPyvq8wPbUhn495 enabled "some:tags:with:colons=some:value:with:colons-and-dashes/and/slashes/yay606-values-001
some:other:tag:with-colons-and-hyphens=MACHINE NAME 
Name=NAMETAG    
backup=true"
i-sMEwh2MXj3q47yWWP enabled "description=RANDOM BUSINESS INT01  
backup=true 
Name=SOMENAME"

I can guarantee each key=value within those quotes are separated by hard/literal tabs, although it may not appear that way with how the StackOverflow code block is displayed in HTML they did carry over into the code block editor, the data under the column Tags is in quotes so that even though they are tab separated they stay within the Tags column. For whatever reason I'm not able to successfully get the desired results.

In my measly attempts, I've been basically capturing everything between the "" as if tabs aren't separated in my regex searches because of my use of wildcards [TAB].*=.*[TAB] is obviously not working because then I'm losing everything in between the first/last occurrence for each line. I've attempted storing them in capture groups without any success.

I'm looking for a unix toolset solution (sed, awk, perl and the like). Any/All help is appreciated!

like image 580
TryTryAgain Avatar asked Dec 06 '25 02:12

TryTryAgain


1 Answers

This will work using any awk in any shell on any UNIX box:

$ awk 'match($0,/".*"/){str=substr($0,RSTART,RLENGTH); gsub(/\t/,"\n",str); $0=substr($0,1,RSTART-1) str substr($0,RSTART+RLENGTH)} 1' file
Name    Monitoring      Tags
i-RBwPyvq8wPbUhn495 enabled "some:tags:with:colons=some:value:with:colons-and-dashes/and/slashes/yay606-values-001
some:other:tag:with-colons-and-hypens=MACHINE NAME
Name=NAMETAG
backup=true"
i-sMEwh2MXj3q47yWWP enabled "description=RANDOM BUSINESS INT01
backup=true
Name=SOMENAME"

It just extracts a string between "s from the current record, replaces all tabs with newlines within that string, then puts the record back together before it's printed.

like image 103
Ed Morton Avatar answered Dec 08 '25 15:12

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!