Heyya
Heyya

Reputation: 57

How to match and replace string following the match via sed or awk

I have a file which I want to modify into a new file using cat. So the file contains lines like:

name "myName"
place "xyz" 

and so on....

I want these lines to be changed to

name "Jon"
place "paris"

I tried to do it like this but its not working:

cat originalFile | sed 's/^name\*/name "Jon"/' > tempFile 

I tried using all sorts of special characters and it did not work. I am unable to recognize the space characters after name and then "myName".

Upvotes: 3

Views: 284

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626690

You may match the rest of the line using .*, and you may match a space with a space, or [[:blank:]] or [[:space:]]:

sed 's/^\(name[[:space:]]\).*/\1"Jon"/;s/^\(place[[:space:]]\).*/\1"paris"/' originalFile > tempFile

Note there are two replace commands here joined with s semicolon. The first parts are wrapped with a capturing group that is necessary because the space POSIX character class is not literal and in order to keep it after replacing the \1 backreference should be used (to insert the text captured with Group 1).

See the online demo:

s='name "myName"
place "xyz"'
sed 's/^\(name[[:space:]]\).*/\1"Jon"/;s/^\(place[[:space:]]\).*/\1"paris"/' <<< "$s"

Output:

name "Jon"
place "paris"

Upvotes: 2

Tyl
Tyl

Reputation: 5252

An awk alternative:

awk '$1=="name"{$0="name \"Jon\""} $1=="place"{$0="place \"paris\""} 1' originalFile

It will work when there're space(s) before name or place.
It's not regex match here but just string compare.
awk separates fields by space characters which including \n or .

Append > tempFile to it when the results seems correct to you.

Upvotes: 0

Related Questions