Search code examples
linuxbashfileecho

Can "echo" stop skipping a line when writing to a file


I'm trying to edit a file with echo command but when I do

echo "hello" >> file.txt

it is skipping a line. It prints the file like:

banana
apple

hello

I'm not sure if this is from echo or if the file ends with an "\n" but I would like to write just below the rest of the text:

banana
apple
hello

EDIT: I see now it is not echo's fault. The file probably ends with a "\n". Is there anyway to bypass this? Can I delete this "\n" or choose in which line I want to write?


Solution

  • Here's another sed script which doesn't hard-code any line numbers.

    sed -i '' '${;s/^$/Hello/;t
    i\
    Hello
    }' file.txt 
    

    Here's a brief breakdown:

    • ${ - the actions in braces should only be applied on the last line (address expression $)
    • s/^$/Hello/ - if this line is empty, replace it with Hello
    • t - if a substitution took place, we are done (branch to end of script)
    • i\Hello - insert Hello on a new line (that is, if we didn't branch on the previous line)
    • } - end of braces

    This is tested on MacOS; syntax on other Unixes will likely be slightly different. (In particular, on Linux, the -i option does not expect or require an argument. Other than that, the script works as such on Debian. Some of the newlines could probably be removed and it would still work, but those are necessary on *BSD sed.)