views:

44

answers:

2

I have a huge number of source files that are all lacking a newline at the end. How do I automatically add a newline to the end of each of them?

Some may already have a newline, so it should only be added if necessary.

I'm probably not looking for code, per se, but just something I can run in Terminal to add the necessary newlines (or some kind of programming or development tool).

alt text

+1  A: 

The following script should do what you want if you give the files as arguments in the command line terminal. Wildcards are allowed:

#!/bin/bash
for f in $*
do
  echo "Appending newline to file $f "
  echo "" >> "$f"
done
txwikinger
This adds a newline to every file whether it's needed or not.
Norman Ramsey
+2  A: 

If you have access to Unix tools, you can run diff to find out which files lack a newline and then append it:

#!/bin/sh
for i
do
  if diff /dev/null "$i" | tail -1 | grep '^\\ No newline' > /dev/null; then 
    echo >> "$i"
  fi
done

I'm relying on diff to produce the message with a \ in the first column, tail to give me the last line of diff's output, and grep to tell me if the last line is the message I'm looking for. If all that works, then the echo produces a newline and the >> appends it to the file "$i". The quotes around "$i" make sure things still work if the filename has spaces in it.

Norman Ramsey