Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

linux - Add a newline only if it doesn't exist

I want to add a newline at the end of a file only if it doesn't exist. This is to prevent multiple newlines at the end of the file.

I'm hoping to use sed. Here are the issues I'm having with my current code:

sed -i -e '/^$/d;$G' /inputfile

echo file1
name1
name2

echo file2
name3
name4
(newline)

when I run my code on to the files;

echo file1
name1
name2
(newline)

echo file2
name3
name4

it adds a newline if it doesn't have one but removes it if it exists... this puzzles me.

question from:https://stackoverflow.com/questions/10082204/add-a-newline-only-if-it-doesnt-exist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

sed

GNU:

sed -i '$a' *.txt

OS X:

sed -i '' '$a' *.txt

$ addresses the last line. a is the append function.

OS X's sed

sed -i '' -n p *.txt

-n disables printing and p prints the pattern space. p adds a missing newline in OS X's sed but not in GNU sed, so this doesn't work with GNU sed.

awk

awk 1

1 can be replaced with anything that evaluates to true. Modifying a file in place:

{ rm file;awk 1 >file; }<file

bash

[[ $(tail -c1 file) && -f file ]]&&echo ''>>file

Trailing newlines are removed from the result of the command substitution, so $(tail -c1 file) is empty only if file ends with a linefeed or is empty. -f file is false if file is empty. [[ $x ]] is equivalent to [[ -n $x ]] in bash.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...