Page 1 of 1

how to awk search and substitution?

Posted: Wed Nov 16, 2022 4:21 pm
by stemsee

i need to search a document for a string , B7= , this is followed by multiline text within single quotes. There are many such blocks A0 - Z9. I need to be able to search for that pattern and then replace the text between the following quotes. The pattern is in a variable and so is the substitution. Any help appreciated

Code: Select all

A0='test|
Title: "food"


Ingredients: delicios


FIELD2:


FIELD3:


FIELD4:


FIELD5:


FIELD6:


FIELD7:


Notes:
'

A1='test|
Title: "food"


Ingredients: delicios


FIELD2:


FIELD3:


FIELD4:


FIELD5:


FIELD6:


FIELD7:


Notes:
'

A2='test|
Title: "food"


Ingredients: delicious


FIELD2:


FIELD3:


FIELD4:


FIELD5:


FIELD6:


FIELD7:


Notes:
'

A3='test|
Title: "food"


Ingredients: delicious


FIELD2:


FIELD3:


FIELD4:


FIELD5:


FIELD6:


FIELD7:


Notes:
'

Re: how to awk search and substitution?

Posted: Wed Nov 16, 2022 7:58 pm
by Burunduk

Maybe this way:

Code: Select all

#!/bin/bash

inputfile="in.txt"
outputfile="out.txt"
pattern="A1"
replacement="1 cup light brown sugar (200 grams)
1 tablespoon all-purpose flour (8 grams)
½ teaspoon salt
1 teaspoon ground cinnamon
1 teaspoon ground ginger"

gawk "{sub(p \"='[^']*'\", p \"='\" r \"'\")};1" RS='\0' p="$pattern" r="$replacement" "$inputfile" >"$outputfile"

It needs gawk, doesn't work with busybox.

Edit: busybox awk works too if RS='\0' is replaced with RS='\1'

It looks like a save file from a note taking app. Are single quotes escaped?
If \' may appear within single quotes, then:

Code: Select all

awk "{gsub(/\\\'/, \"\\1\");sub(p \"='[^']*'\", p \"='\" r \"'\");gsub(/\\1/, \"\\\'\")};1" RS='\1' p="$pattern" r="$replacement" "$inputfile" >"$outputfile"