Clarification needed for a SED one liner

I want to use SED to replace all new line characters of a file, I googled and found this one liner

sed '{:q;N;s/\n//g;t q}' infile

what do :q;N; and t q mean in this script?

:q is a label (called q), N reads the next line (the two lines now also contain the newline character, which the substitution (s) will remove), t q go's back (t) to the label q in the event that the substitution (s) had modified anything.

1 Like

Oh, after I tested the script, it did not delete new line characters, the file is unchanged.
How to delete new line characters using SED?

What exactly u want to do? Are u looking to merge all lines or u have ^M characters in your file which needs to be deleted?

Hi, ROHON
I want to delete the last new line character(\n) in the file. what's ^M by the way?

The file might be unchanged because you didn't save it?

If your sed has the -i option, use it to overwrite the file with the changes, otherwise write to a temporary file and then replace the original one. Otherwise use perl or ed to make the changes and save the file.

To replace all new line characters of a file you can use xargs:

xargs < file > newfile
1 Like