brastein
brastein

Reputation: 77

Search for specific line of text file, replace up to a certain character

In file my_file.ini, I want to modify the line starting with dataspecs like so:

replace dataspecs old_val old stuff blah blah ! blah blah with

dataspecs $new_val ! blah blah, where new_val is a bash variable, and everything after the ! is preserved. Also, I don't know the value of old_val.

I don't care whether it's sed or awk or just bash, I'm just looking for a simple answer that I can understand. I would really appreciate a solution, especially if you could explain what the code of the solution means, for someone who is just learning sed and awk (not the easiest code to look at). Thanks!

Upvotes: 1

Views: 552

Answers (3)

anubhava
anubhava

Reputation: 784928

Use sed:

sed -i.bak "s/^\( *dataspecs \)[^\!]*/\1${new_val} /" my_file.ini

PS: I am using inline flag -i of sed for inline editing, this will save the modified file.

Upvotes: 1

konsolebox
konsolebox

Reputation: 75458

I'd suggest this form of sed:

sed "s/^\\(dataspecs \\)[^!]*\\( !.*\\)/\\1${new_val}\\2/" my_file.ini

Add -i option if you want to modify the file directly.

sed -i "s/^\\(dataspecs \\)[^!]*\\( !.*\\)/\\1${new_val}\\2/" my_file.ini

Upvotes: 1

Jotne
Jotne

Reputation: 41446

awk '/dataspecs old_val/ {$2="$new_val"}1' my_file.ini

Upvotes: 0

Related Questions