Search code examples
fish

How can I replace the final character in a document with a ]?


How can I replace the final character of a file with a ]?

For example, if the document content looked like this:

This is the first line with a full stop.
This is the second line with a full stop.
This is the third line with square bracket.

I would want it to look like this afterwards:

This is the first line with a full stop.
This is the second line with a full stop.
This is the third line with square bracket]

Solution

  • You may specify line numbers, ranges or even the last line where you want to perform search and replace operations with sed:

    This will replace the final , char with ] only on the last line:

    sed '$ s/,$/]/'
    

    Here, the $ char tells sed to only replace on the last line.

    The sed '1 s/,$/]/' command will do that only on Line 1, and sed '1,4 s/,$/]/' will do that on lines 1 through 4.