linux - Bash Scripting: Replace (or delete) string in a file if line starts with (or matches) another string -


assuming ini-style file this,

[group] icon=xxx.ico title=an image editor description=manipulates .ico, .png , .jpeg images 

i want replace/delete ".ico" in line starts (or matches) "icon="

i trying this:

oldline="`cat "$file" | grep "icon="`" newline="`echo "$oldline" | tr ".ico" ".png"`" cat "$oldfile" | tr "$oldline" "$newline" > $file 

then realized tr works different thought. not tradicional "replace that" function. guess correct way using sed. but:

  • ive never used sedbefore. no idea how works. overkill?
  • if indicated way using sed, given powerful, there elegant way accomplish rather "fetch line -> modify line -> replace oldline newline in file" approach?

notes:

  • i cant replace ".ico" globally, know lot easier, must restrict replace icon line, otherwise description line changed too.
  • im new shell scripting in linux, im looking not solution itself, "proper" way it. elegant, easy read, conventional, etc

thanks in advance!

edit:

thank guys! here final script, reference:

#! /bin/bash # fix following warning in ~/.xsession-errors # gnome-session[2035]: eggsmclient-warning: desktop file '/home/xxx/.config/autostart/skype.desktop' has malformed icon key 'skype.png'(should not include extension)  file="$home/.config/autostart/skype.desktop"  if [ -f "$file" ] ;     if `cat "$file" | grep "icon=" | grep -q ".png"` ;         sed -i.bak '/^icon=/s/\.png$//' "$file"         cp "$file" "$pwd"         cp "${file}.bak" "$pwd"          else         echo "nothing fix! (maybe fixed already?)"     fi   else     echo "skype not installed (yet...)" fi 

much sleeker original! thing regret sed backup not preserve original file timestamp. can live that.

and, record, yes, ive created script fix actual "bug" in skype packaging.

something following in sed should need. first check if line starts icon= , if run s command (i.e. substitute).

sed -i '/^icon=/s/\.ico$/.png/' file 

edit: sed script above can written this:

/^icon=/ {             # run following block when matches     s/\.ico$/.png/     # substitute '.ico' @ end of line '.png' } 

see this page more details on how restrict when commands run.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -