How to Prevent Curl from Stripping Newlines
This article explains how to prevent the curl
command-line tool from stripping newlines and carriage returns when
reading data from a file. By default, curl removes these
line breaks when using standard data flags, but you can preserve the
original formatting of your payload by using the correct command-line
options.
The Problem with Standard Curl Data Flags
When you send data from a file using the -d or
--data flags, curl automatically strips all
carriage returns and newline characters, merging your file contents into
a single line.
For example, this standard command will strip newlines:
curl -d "@myfile.txt" https://api.example.com/endpointSolution 1: Use the –data-binary Flag
The most direct way to prevent curl from stripping
newlines is to use the --data-binary flag instead of
-d or --data. This tells curl to
transmit the file exactly as it is stored on your disk, preserving all
formatting, spaces, and line breaks.
curl --data-binary "@myfile.txt" https://api.example.com/endpointSolution 2: Use –data-urlencode for URL-Encoded Data
If your target API requires the data to be URL-encoded, but you still
need to preserve the line breaks inside the payload, use the
--data-urlencode flag. This will convert the newlines into
%0A (or %0D%0A) instead of deleting them.
curl --data-urlencode "content@myfile.txt" https://api.example.com/endpoint(Note: The content prefix before the @
symbol specifies the key name for the POST parameter).
Solution 3: Use Multipart Form Data
If you are uploading the file to a server that accepts
multipart/form-data (like a standard file upload input in a web form),
use the -F flag. This method naturally preserves all line
breaks within the file.
curl -F "file=@myfile.txt" https://api.example.com/endpoint