how to awk search and substitution?

For discussions about programming, and for programming questions and advice


Moderator: Forum moderators

Post Reply
User avatar
stemsee
Posts: 658
Joined: Sun Jul 26, 2020 8:11 am
Location: lattitude 0
Has thanked: 162 times
Been thanked: 104 times
Contact:

how to awk search and substitution?

Post 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:
'
Burunduk
Posts: 244
Joined: Thu Jun 16, 2022 6:16 pm
Has thanked: 6 times
Been thanked: 122 times

Re: how to awk search and substitution?

Post 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"

Post Reply

Return to “Programming”