Michel
Michel

Reputation: 23

sed looses right part of the line

I have some difficulties with the sed command on Unix AIX IBM). It's seems also on linux...

here is a line of my file, that i would change :

# id=<$IdEDFRGB.RR '" fgg t uj67575 uj:$ g re ee >

it should be after the subsitution :

# id=<$Id22 02 21 17:13$  g re ee >f rgrge

when i use this sed command (after initialize the DT variable) :

sed "s/<\$Id.*\$/<\$Id${DT}\$/g"

I obtain :

# id=<$Id22 02 2021 17:41$

I loose the right part. Someone could help me ?

thx

Upvotes: 2

Views: 45

Answers (2)

Barmar
Barmar

Reputation: 781078

You need to escape the backslashes in the regexp so they're treated as literal backslash by the shell's string parser, and then they will escape the $ in the regexp. You also need to escape the $ in the regexp so that they don't start a variable expansion.

sed "s/<\\\$Id.*\\\$/<\$Id${DT}\$/g"

Upvotes: 3

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

If you use echo ".*\$", you will see .*$, the pattern matches any text up to the string end, that's why your "right side" is eaten up. $ in a double quoted string is used to expand variables and in order to use a literal $, you need to use a "\$" char combination. In order to introduce a \$ literal text into a double quoted string, you need "\\$".

Use single quotes to avoid these issues, only use double quotes around the variable:

sed 's/\(<\$Id\).*\(\$\)/\1'"$DT"'\2/' file

Here, \(<\$Id\) is a capturing group 1 (\1) that captures <$Id literal text and \(\$\) is a capturing group 2 (\2) that captures a $ char. The $DT is within double quotes and is expanded correctly.

Using capturing groups, you avoid having to double the literal text both inside the pattern and the replacement.

Upvotes: 0

Related Questions