Atomiklan
Atomiklan

Reputation: 5464

sed replace end of specific string in file

I have a hash file that takes the form of:

SHA1(disk.iso)= 43798473890473280573920473902472083947320

I need to replace the old hash with the new hash.

I've been trying to modify some old code with no luck:

sed -i 's/SHA1(disk.iso)"[^+]*"/"'" $HASH"'"/' manifest

Any thoughts here?

* UPDATE *

The sting listed above is correct:

SHA1(disk.iso)= (some SHA1 hash here. Note the space after the equal sign.)

Here is the current code:

sed -i "s/\(SHA1(disk.iso)=\).*/\1 $HASH/" manifest

but still nothing. This does not modify the line in question.

* SOLUTION *

THIS WORKS:

sed -i "s/\(SHA1(disk.iso)=\).*/\1 $HASH/" manifest

I just had the file name wrong. Thank you Janos

Upvotes: 1

Views: 1570

Answers (3)

janos
janos

Reputation: 124824

Here you go:

sed -i "s/\(SHA1(disk.iso)=\).*/\1 $HASH/" manifest

That is:

  • Capture the filename within \(...\), and match the rest of the line with .*
  • Replace the pattern (the entire line) with the captured filename \1, and append the $HASH
  • The whole thing within double quotes, so that shell variables are expanded.

Here's another variation to do the same thing:

sed -i "/^SHA1(disk.iso)/ s/=.*/= $HASH/" manifest

That is:

  • For lines starting with SHA1(disk.iso)
  • Replace the = sign and everything after it with = $HASH

Upvotes: 2

Floris
Floris

Reputation: 46445

Two steps:

  1. find the right line
  2. replace the number in that line with a new number

Typically you do this with

cat myHashFile.txt | sed '/SHA1(disk.iso)/  {s/\d+/'$HASH'/}' > newHashFile.txt

The first term in /.../ in general takes a regular expression "apply what follows to lines meeting this condition"

The second part in {..} is the command:

s     substitute
\d    any digit
\d+   one or more digits (greedy)
$HASH replace with the contents of the $HASH variable

Upvotes: 1

Igor Chubin
Igor Chubin

Reputation: 64623

You regular expression seems to be strange. You use to many quotes.

You can just do (if you now the hashes):

sed -i "s/$OLDHASH/$NEWHASH" manifest

And if you don't know them and just want to replace any line with SHA1(disk.iso), you can write:

sed -i "s/\(SHA1(disk.iso)=\).*/\1 $HASH/"

\(\) here mean backreferences; that means that you save the line in a register, that will be later used using \1. Of course, you could write directly:

sed -i "s/SHA1(disk.iso)=.*/SHA1(disk.iso) $HASH/"

but in this case it would be impossible to write something like disk[123].iso to match several ISOs at once.

Upvotes: 1

Related Questions