How do I find files that do not end with a newline/linefeed?

后端 未结 12 1270
广开言路
广开言路 2021-02-01 03:45

How can I list normal text (.txt) filenames, that don\'t end with a newline?

e.g.: list (output) this filename:

$ cat a.txt
asdfasdlsad4rand         


        
12条回答
  •  难免孤独
    2021-02-01 04:15

    Most solutions on this page do not work for me (FreeBSD 10.3 amd64). Ian Will's OSX solution does almost-always work, but is pretty difficult to follow : - (

    There is an easy solution that almost-always works too : (if $f is the file) :

    sed -i '' -e '$a\' "$f"

    There is a major problem with the sed solution : it never gives you the opportunity to just check (and not append a newline).

    Both the above solutions fail for DOS files. I think the most portable/scriptable solution is probably the easiest one, which I developed myself : - )

    Here is that elementary sh script which combines file/unix2dos/tail. In production, you will likely need to use "$f" in quotes and fetch tail output (embedded into the shell variable named last) as \"$f\"

    if file $f | grep 'ASCII text' > /dev/null; then
        if file $f | grep 'CRLF' > /dev/null; then
            type unix2dos > /dev/null || exit 1
            dos2unix $f
            last="`tail -c1 $f`"
            [ -n "$last" ] && echo >> $f
            unix2dos $f
        else
            last="`tail -c1 $f`"
            [ -n "$last" ] && echo >> $f
        fi
    fi
    

    Hope this helps someone.

提交回复
热议问题