sedescapingsubstitutionstring-substitution

Append specific caracter at the end of each line


I have a file and I want to append a specific text, \0A, to the end of each of its lines.

I used this command,

sed -i s/$/\0A/ file.txt

but that didn't work with backslash \0A.


Solution

  • Your command should be fixed by simply enclosing s/$/\0A/ in single quotes (') and escaping the backslash (with another backslash):

    sed -i 's/$/\\0A/' file.txt
    

    Notice that the surrounding 's protect that string from being processed by the shell, but the bashslash still needed escape in order to protect it from SED itself.

    Obviously, it's still possible to avoid the single quotes if you escape enough:

    sed -i s/$/\\\\0A/ file.txt
    

    In this case there are no single quotes to protect the string, so we need write \\ in the shell to get SED fed with \, but we need two of those \\, i.e. \\\\, so that SED is fed with \\, which is an escaped \.

    Move obviously, I'd never ever suggest the second alternative.