0

let's say that I have a file with the following format:

name type 3425sdfsg125 url

between every entry (i.e name and type) is a variable amount of whitespace characters.

I want to replace the hash value 3425... with another hash value that is stored in ${hash} variable:

hash=48956sdglj23

the result should be:

name type 48956sdglj23 url

how would one do such a thing using sed?

2 Answers2

0

As far as I understand, you do not have the exact value to replace? Does this work?

sed -i "s/y   .* z/y   $hash z/g" foo
Andrew
  • 136
  • 2
  • Well, I just checked and it worked for me: `$ cat foo` `name type 3425sdfsg125 url` `$ sed "s/e .* u/e $hash u/g" foo` `name 48956sdglj23 url` If this does not work, is there a more full example of what needs to be accomplished? – Andrew Apr 16 '20 at 14:28
  • Maybe it would be better like this: `sed "s/type .* url/type $hash url/g"` So it changes everything between "type " and " url" as ".*" represents any number of any characters. – Andrew Apr 16 '20 at 14:41
  • this works but is it possible to keep the whitespace as in the original file? thanks again – JerryThePineapple Apr 16 '20 at 14:45
  • Yeah, in my examples I have the same whitespaces as in the file. Just need to include them to the command. As you can see, in the original answer, there are three whitespaces after "y" and that works. – Andrew Apr 16 '20 at 14:50
0

Robustly with GNU sed:

$ echo 'name    type   3425sdfsg125    url' |
    sed -E 's/^(\s*name\s+type\s+)\S+(\s+url\s*)$/\1'"$hash"'\2/'
name    type   48956sdglj23    url

and any POSIX sed:

$ echo 'name    type   3425sdfsg125    url' |
    sed 's/^\([[:space:]]*name[[:space:]]\{1,\}type[[:space:]]\{1,\}\)[^[:space:]]\{1,\}\([[:space:]]\{1,\}url[[:space:]]*\)$/\1'"$hash"'\2/'
name    type   48956sdglj23    url
Ed Morton
  • 188,023
  • 17
  • 78
  • 185