AlwynIsPat
AlwynIsPat

Reputation: 739

Changing a line in a text file if it exists

I know you can change a line in a text file using sed in bash that shows something like;

name="applicationname" //this is not the issue (it varies, thats why i use a var)

Depiction: http://google.com or Depiction: http://yahoo.com //some times the 'value' in depiction varies

to

Depiction: http://mysite.com/depiction.php?package=applicationname //this is the format i would like to achieve

by using sed, but I'm not entirely sure how to implement sed. http://www.gnu.org/software/sed/

EDIT: This is what i just came up with

sed -i "s!Depiction:.*!Depiction: http://mysite.com/depiction.php?package=$name!" ./inputfile

What if in this particular text file, there isnt a 'Depiction:'? how do i insert a line: Depiction: http://mysite.com/depiction.php?package=applicationname ?

Upvotes: 1

Views: 1209

Answers (5)

AlwynIsPat
AlwynIsPat

Reputation: 739

I've managed to come up with the answer with many trials and errors... so just to share. :)

if grep -Fq "Depiction:" ./file
then
sed -i "s!Depiction:.*!Depiction: http://mysite.com/depiction.php?package=$name" ./file
else
sed -i 1i"Depiction: http://mysite.com/depiction.php?package=$name" ./file
fi

Upvotes: 1

potong
potong

Reputation: 58483

This might work for you:

sed -i '/Depiction:.*/{h;s||Depiction: http://mysite.com/depiction.php?package='"$name"'|};$!b;x;/./{x;q};x;a\Depiction: http://mysite.com/depiction.php?package='"$name" ./inputfile

or perhaps as the barebones:

sed -i '/foo/{h;s//FOO/};$!b;x;/./{x;q};x;a\FOO' file

In essence:

  • If foo exists, make a copy in the hold space (HS) and carry out substitution.
  • At end of file ($) check the hold space for evidence or previous substitution and if none append a line.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 247012

You could try it this way: remove all instances of "Depiction:" then append the line you want

{
  grep -v "Depiction:" filename
  echo "Depiction: ..."
} > newfile && mv newfile filename

Upvotes: 1

Amadan
Amadan

Reputation: 198436

Delete it, then add, if you don't care about the order. Or use awk:

awk 'BEGIN{replacement="Depiction: http://mysite.com/depiction.php?package=applicationname"}/^Depiction:/{print replacement;found=1}!/^Depiction:/{print}END{if(!found)print replacement}' < file

or any other higher-order language.

Upvotes: 0

bukzor
bukzor

Reputation: 38502

sed is most valuable for simple substitutions. Once you have logic like "if not found, do X", you should move to a more general-purpose language. I like Python:

from sys import argv, stdout

filename = argv[1]
depiction_found = False
for line in open(filename):
    line.replace('foo', 'bar') #I'm not too sure what you're really trying to do
    if line.startswith("Depiction: "):
        depiction_found = True
    stdout.write(line)

if not depiction_found:
    stdout.write("Depiction: <correct value here>\n")

Upvotes: 0

Related Questions