Note that in standard sed
, sed 's/[\t]*$//'
removes all backslash and t
characters from the end of the line. The GNU implementation of sed
only does it when there's a POSIXLY_CORRECT
variable in its environment.
sed 's/\t*$//'
is unspecified, but at least with GNU sed
, that happens to remove trailing TABs whether POSIXLY_CORRECT
is in the environment or not.
Here you could do:
sed $'s/\t*$/\r/'
Using the ksh93-style $'...'
form of quotes inside which things like \t
or \r
are expanded to TAB and CR respectively. That's now supported by many other shells and will be in the next version of the POSIX standard for sh
.
If you have TAB and CR characters in shell variables, which you could do without $'...'
for instance with:
eval "$(printf 'TAB="\t" CR="\r"')"
You could do:
sed "s/$TAB*\$/$CR/"
But that has to be within double-quotes. Inside single quotes, no expansion is performed.
Now, in the unlikely event that the input doesn't end in a LF character (which would make it invalid text in Unix), those (with GNU sed
at least) would produce a file that ends in a CR character, making it invalid in DOS as well.
To convert the text files from Unix to DOS, you could use the unix2dos
utility instead which wouldn't have the problem:
sed $'s/\t*$//' | unix2dos
Or use perl
's sed
mode:
perl -pe 's/\t*$//; s/\n/\r\n/'
perl -p
works like sed
in that it runs the code for each line of input, except that in perl
the pattern space ($_
there) has the full line including the line delimiter. It also supports those \t
, \n
, \r
escapes (while standard sed
only supports \n
and only in regular expressions), and can cope with non-text files.
$CR
in the file is because variables are not expanded inside single quotes, only in double quotes. – Barmar Apr 13 '23 at 15:27\t
in the expression, why not use ``\r` as well? – Sammitch Apr 14 '23 at 22:21>>
appending into a different file? Wouldn't you want to create a new one? – jubilatious1 Apr 17 '23 at 10:31$
in Git Bash for Windows will match on both LF and CRLF, while in WSL (Ubuntu distro) it will match on LF only. – MJ713 Apr 26 '23 at 17:28