FriendlyStudent
FriendlyStudent

Reputation: 13

How do I replace the first occurance of a key value in a config file with sed?

I would like to change the application name in a config file. Name= has multiple occurrences, but I only want to change the first. For reference, the config file has the following structure:

[Desktop Entry]
Version=1.0
Name=name
Name[ar]=...
[...]
[Desktop Action new-window]
Name=Open a New Window
[...]

What I tried so far is the bash command sed:

sudo sed "0,/Name/s/=.*\$/=Replace/" app_desktop_configs/std_firefox.desktop

which mostly did what I wanted, but also replaces the version number:

[Desktop Entry]
Version=Replace
Name=Replace
Name[ar]=...
[...]

Alternative solution to sed are also welcome :)

Upvotes: 1

Views: 129

Answers (3)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -E '/(name=).*/{s//\1Replace/;:a;n;ba}' file

Or:

sed -E 's/(name=).*/\1Replace/;T;:a;n;ba' file

Or:

sed  -E 'x;/./{x;b};x;/(name=).*/h;s//\1Replace/' file

All the above solutions amend the first occurrence of name and then continue to the end of the file making no further amendments.

Upvotes: 0

Timur Shtatland
Timur Shtatland

Reputation: 12347

A Perl solution:

perl -i.bak -pe 'unless ( $cnt ) { s{Name=name}{Name=replace} and $cnt++; } ' infile

The Perl one-liner uses these command line flags:
-e : Tells Perl to look for code in-line, instead of in a file.
-p : Loop over the input one line at a time, assigning it to $_ by default. Add print $_ after each loop iteration.
-i.bak : Edit input files in-place (overwrite the input file). Before overwriting, save a backup copy of the original file by appending to its name the extension .bak.

SEE ALSO:
perldoc perlrun: how to execute the Perl interpreter: command line switches
perldoc perlre: Perl regular expressions (regexes)

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 140940

So match exactly Name= not =.*

sed '0,/^Name=/s/^Name=.*/Name=Replace/'

Upvotes: 1

Related Questions