Add a newline only if it doesn't exist

前端 未结 8 775
温柔的废话
温柔的废话 2021-01-31 08:49

I want to add a newline at the end of a file only if it doesn\'t exists, this is to prevent multiple newlines at the end of the file.

I\'m hoping to use sed. Here\'s the

8条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-31 08:57

    Using Bash only

    You can use Command Substitution (remove trailing newlines) with Here Strings (appends newline):

       Command Substitution
           Command substitution allows the output of a command to replace the command  name.   There  are  two
           forms:
    
              $(command)
           or
              `command`
    
           Bash  performs  the expansion by executing command in a subshell environment and replacing the com-
           mand substitution with the standard output of the command,  with  any  trailing  newlines  deleted.
           Embedded newlines are not deleted, but they may be removed during word splitting.  The command sub-
           stitution $(cat file) can be replaced by the equivalent but faster $(< file).
    
    
    
       Here Strings
           A variant of here documents, the format is:
    
              [n]<<

    Here's how it works:

    cat <<<"$(

    Output to file:

    cat <<<"$(outputfile
    

    If you need inputfile and outputfile to be the same file name, you have a couple options - use sponge command, save to temporary variable with more command substitution, or save to temporary file.


    Using Sed

    Others have suggested using

    sed '$a\' inputfile
    

    which appends nothing to the last line. This is fine, but I think

    sed '$q' inputfile
    

    is a bit clearer, because it quits on the last line. Or you can do

    sed -n 'p'
    

    which uses -n to suppress output, but prints it back out with p.

    In any of these cases, sed will fix up the line and add a newline, at least for GNU and BSD sed. However, I'm not sure if this functionality is defined by POSIX. A version of sed might just skip your line without a newline since a line is defined as

    A sequence of zero or more non- characters plus a terminating character.

提交回复
热议问题