I want to write some pre-defined texts to a file with the following:
text="this is line one\n this is line two\n this is line three" echo -e $text > filename
I'm expecting something like this:
this is line one this is line two this is line three
But got this:
this is line one this is line two this is line three
I'm positive that there is no space after each \n
, but how does the extra space come out?
Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string. Python's indentation rules for blocks do not apply to lines inside a multiline string.
An alternative to using triple quotes ( ''' ) to create a multiline string is to enclose the entire string in brackets ( () ) and split our string using the enter button. This will automatically indent each line correctly as everything within the brackets is be considered one block of code.
Bash Escape Characters For example, if we have a multiline string in a script, we can use the \n character to create a new line where necessary. Executing the above script prints the strings in a new line where the \n character exists.
Heredoc sounds more convenient for this purpose. It is used to send multiple commands to a command interpreter program like ex or cat
cat << EndOfMessage This is line 1. This is line 2. Line 3. EndOfMessage
The string after <<
indicates where to stop.
To send these lines to a file, use:
cat > $FILE <<- EOM Line 1. Line 2. EOM
You could also store these lines to a variable:
read -r -d '' VAR << EOM This is line 1. This is line 2. Line 3. EOM
This stores the lines to the variable named VAR
.
When printing, remember the quotes around the variable otherwise you won't see the newline characters.
echo "$VAR"
Even better, you can use indentation to make it stand out more in your code. This time just add a -
after <<
to stop the tabs from appearing.
read -r -d '' VAR <<- EOM This is line 1. This is line 2. Line 3. EOM
But then you must use tabs, not spaces, for indentation in your code.
If you're trying to get the string into a variable, another easy way is something like this:
USAGE=$(cat <<-END This is line one. This is line two. This is line three. END )
If you indent your string with tabs (i.e., '\t'), the indentation will be stripped out. If you indent with spaces, the indentation will be left in.
NOTE: It is significant that the last closing parenthesis is on another line. The END
text must appear on a line by itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With