Comments on: Sanitizing files with no trailing newline https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/ Proudly uncool and out of fashion Fri, 03 Oct 2014 13:47:44 +0000 hourly 1 https://wordpress.org/?v=5.8.2 By: waldner https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/#comment-25139 Fri, 03 Oct 2014 13:47:44 +0000 http://backreference.org/?p=1363#comment-25139 In reply to Todd Partridge.

That's an *extremely* inefficient way of doing it (not to mention that cat's -t and -e are GNU extensions and may not be available).
If you really want to go that route, then do:

tail -n1 testfile | cat -te | grep -q \\\$$
]]>
By: Todd Partridge https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/#comment-25138 Fri, 03 Oct 2014 12:53:32 +0000 http://backreference.org/?p=1363#comment-25138 cat -t -e testfile | tail -n1 | grep -q \$$ ]]> By: waldner https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/#comment-1208 Thu, 05 Aug 2010 17:01:44 +0000 http://backreference.org/?p=1363#comment-1208 In reply to gregor.

Thanks.

The sed method is not realiable: for example, it does not work with GNU sed (even replacing -E with its equivalent in GNU sed -r). And besides that, sed needs to read the whole file, which is something that we specifically want to avoid. Along the same lines,

awk 1 file

which is mentioned in the article, produces correct output regardless of whether the input has a trailing newline or not. But again, that needs to read the whole file.

And regarding the ed solution: it still reads the whole file so it's out of the article's scope, but it does work. It can be rewritten more portably as

printf '%s\n' H '$s/\(.*\)/\1/' w q | ed file

which, at least on GNU ed, prints a "Newline appended" message to let the user know what it did.

]]>
By: gregor https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/#comment-1204 Thu, 05 Aug 2010 15:41:37 +0000 http://backreference.org/?p=1363#comment-1204 Here are two more alternatives:

# note: ed will read entire file into memory
[[ -s file ]] && ed -s file <<< $'H\n$s/\(.*\)/\\1/\nwq'

sed -E -i "" '$s/(.*)/\1/' file

]]>
By: waldner https://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/#comment-1082 Wed, 28 Jul 2010 16:22:08 +0000 http://backreference.org/?p=1363#comment-1082 In reply to gregor.

Hi Gregor,

thanks for the comment. Yes that will work, perhaps a bit heavyweight (3 processes) but it's good to list alternatives.

]]>