How to replace part of a regex with sed?

Viewed 147

In a file test.txt I have the following text line

COPYRIGHT (c) 2020 alex4200

in which I want to use sed to find that line and to replace the year 2020 by the year 2021. I have tried the following expression:

sed -i -E  "s/COPYRIGHT .*(\d\{4\}) alex4200/2021/" test.txt

but it did not change the text in the file test.txt. What am I missing?

1 Answers

First thing first \d is not supported in sed you need to use [0-9]. Then your expression is also not correct(even you fix \d it will not work with your tried code), so I have corrected it as per your shown samples. With your shown samples, please try following.

sed -E 's/^([^ ]* +[^ ]*) +([^\s]*) +(.*)$/\1 2021 \3/' Input_file

Once you are happy with results(which will be shown on terminal) you can use -i option to do inplace save in above code.

Explanation: Simple explanation would be, using sed's backreference capability while substitution. In first part of substitution part, making 3 back references as per shown samples, where 2nd back reference will have 2020 value in it, while doing substitution putting 2021 value there.

Explanation of regex:

^([^ ]* +[^ ]*)  ##From starting of value creating 1st back reference which will match values just before 2nd occurrence of space.
 +               ##Matching 1 or more occurrences of spaces here.
([^\s]*)         ##Creating 2nd capturing group which will match everything till space comes, to catch 2020 basically.
 +               ##Matching 1 or more occurrences of spaces here.
(.*)$            ##Matching everything till last here and creating 3rd back reference here.

Fixing OP's attempts:

sed -E  's/^(COPYRIGHT .*\(c\))\s+([^ ]*)\s+(.*)/\1 2021 \3/' Input_file

OR to match digits with shown samples, following could be used:

sed -E 's/^(COPYRIGHT\s+\(.*\))\s+([0-9]{4})(.*)$/\1 2021 \3/' Input_file
Related