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

Time:05-21

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 :)

CodePudding user response:

So match exactly Name= not =.*

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

CodePudding user response:

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)

  • Related