How to escape newline in the commandline?

2

1

I need to do this:

$ echo '
File
Contents
' > my-file

The problem is that the resulting file contains a newline at the beginning and at the end.

I tried this but didn't work:

$ echo '\
File
Contents\
' > my-file

What can I do?

ChocoDeveloper

Posted 2012-07-23T16:45:10.840

Reputation: 2 327

Answers

3

Maybe you can use a HERE document?

cat << '==end' > my-file
File
Contents
==end

choroba

Posted 2012-07-23T16:45:10.840

Reputation: 14 741

Yes this looks good. But how to send the result to a file? Right now it's only printing it on the screen. – ChocoDeveloper – 2012-07-23T17:03:12.283

@ChocoDeveloper: Use redirection. Answer updated. – choroba – 2012-07-23T17:05:12.343

2

Another simple answer not mentioned is:

echo -e "Line 1\nLine 2"

The -e option causes echo to interpret backslash escape sequences.

Michael Hampton

Posted 2012-07-23T16:45:10.840

Reputation: 11 744

1

printf "%s\n%s\n%s\n" "Line 1", "Line 2", "Line 3"

Peter

Posted 2012-07-23T16:45:10.840

Reputation: 279

I need to be able to paste the file contents without any change, I can't separate it into lines. And I need to be able to execute this as a command, I don't want to open vim and paste it manually. – ChocoDeveloper – 2012-07-23T16:51:26.683

I think I cannot understand what you want to do. Do you want to just copy some files to another one? – Peter – 2012-07-23T16:52:49.957

I want to copy/paste file contents (ie: something I don't want to write by hand each time, like a config file) into a command to create the file, to automate an installation. – ChocoDeveloper – 2012-07-23T16:54:11.017

Then, a good example, is to use grep. For example, you find the line you want and then, count the lines you want to copy: grep myline -A6 will copy from "myline" and the next 6 lines. – Peter – 2012-07-23T16:55:19.637

1

I would use cat instead:

cat > file

Paste what you want to go into file and finish with Ctrl+d on an empty line.

Thor

Posted 2012-07-23T16:45:10.840

Reputation: 5 178

But I want to do everything in a single command. If I can paste to a file, I could as well just have pasted into the file I need. – ChocoDeveloper – 2012-07-23T16:57:09.733

@ChocoDeveloper: ok, you're probably looking for the heredoc option then, see choroba's answer but with > file after the first ==end. – Thor – 2012-07-23T17:04:01.330