I need to replace any matching pattern after the last space. I've an ssh certificate file like:

ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAgePsBdieYnkI6dvMLG5qAl+UnOXo8mV0JmthWTNZ7+REAAAADAQABAAABAQC0aFhFni8pfoRiwt5O1ZVU6G0Xb+iX3D+A7uEItzLAygf7V/Se6tUg3SlUWf85G4S5vceZzbzTXbNso+vCaYc+RA0xwaxDBDHomdJVzpK/TUL+lV63V51vhvaM2redU+fYDGuUHUbVjt0Y4qaHBr6R4Rh0GujbL6U+/eq1yQ52VGD34f1eldt56xvykP1HAfs158oDcCL1lnJ26SPMzN38X6RCl/vAZn8UmOntmpa2LVT+j8kf1lKAQdpGYGbwZybo8LCYL2lyv3LTw1slULZsoKnazuZOKoaTxEziJfvr79jS9sNctqxBMPkeTDxUuLdd3URpiCCfpRcmKH+owAz3AAAAAAAAAAAAAAACAAAAGHZtdHN0aWlxMS5jZWRlbGdyb3VwLmNvbQAAACkAAAAYdm10c3RpaXExLmNlZGVsZ3JvdXAuY29tAAAACXZtdHN0aWlxMQAAAABfaeD6AAAAAGFxvY= ssh_host_rsa_key.pub

Here, at the end of the file I've ssh_host_rsa_key.pub or it can be something different like /home/user/ssh_host_rsa_key.pub. I want to find it and replace by another string.

How can I find and replace everything starting from last space? With sed or awk or anything else...

Thanks in advance.

  • Is it guaranteed that the comment at the end of the line never contains any spaces?
    – Kusalananda
    Oct 8 '20 at 9:37
  • I tried with different files containing one empty line and no empty lines. Following codes worked: sed 's/ [^ ]*$/ new text/' < file and sed -E 's/(^.*) [^ ]+$/\1 replacement_text/' file.txt
    – mufit
    Oct 8 '20 at 9:53

You could try

sed -E 's/(^.*) [^ ]+$/\1 replacement_text/' file.txt

This will match

  • "anything from the start of the line" (the ^.* pattern, placed in a "capture group" ( ... )),
  • then a space,
  • and then "anything but a space ([^ ]) up to the end of the line" (the + behind the [...] means "one or more such characters", and the $ is an anchor that indicates "end-of-line"),

and replace the latter part with your replacement text. The former part is replaced "with itself" thanks to the capture group \1.

  • Thanks for the explanation. sed -E 's/(^.*) [^ ]+$/\1 replacement_text/' file.txt works.
    – mufit
    Oct 8 '20 at 9:51
  • 1
    @mufit You're welcome. If you found any of the answers useful, please consider accepting one of them so that others facing a similar problem may find it more easily.
    – AdminBee
    Oct 8 '20 at 9:55

This works when there are two space delimited fields at the start of the line. The third field is allowed to be absent.

awk '{print $1 " " $2 " new text"}' < file

This replaces after the last space no matter how many spaces there are in the line:

sed 's/ [^ ]*$/ new text/' < file
  • Thanks for the answer. Second command worked perfectly. sed 's/ [^ ]*$/ new text/' < file
    – mufit
    Oct 8 '20 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.