View Full Version : Adding \n newline control character onto a bash string
CD-RW
2nd July 2009, 07:50 AM
I'm trying to build a small text file on-the-fly with bash. It has several lines, each one ending with a newline character.
So far I have:
[root@F10]# LINE1="This is line 1"
[root@F10]# LINE2="This is line 2"
[root@F10]# LINE3="This is line 3"
[root@F10]#
[root@F10]# FILE="${LINE1}${LINE2}${LINE3}"
[root@F10]# echo $FILE
This is line 1This is line 2This is line 3
[root@F10]#
[root@F10]# FILE="${LINE1}"\n"${LINE2}"\n"${LINE3}"
[root@F10]# echo $FILE
This is line 1nThis is line 2nThis is line 3
I can't get the \n newline characters onto the end of the lines. Am I missing something?
I want the output to look like:
This is line 1
This is line 2
This is line 3
fav0nius
2nd July 2009, 08:27 AM
I'm trying to build a small text file on-the-fly with bash. It has several lines, each one ending with a newline character.
So far I have:
[root@F10]# LINE1="This is line 1"
[root@F10]# LINE2="This is line 2"
[root@F10]# LINE3="This is line 3"
[root@F10]#
[root@F10]# FILE="${LINE1}${LINE2}${LINE3}"
[root@F10]# echo $FILE
This is line 1This is line 2This is line 3
[root@F10]#
[root@F10]# FILE="${LINE1}"\n"${LINE2}"\n"${LINE3}"
[root@F10]# echo $FILE
This is line 1nThis is line 2nThis is line 3
I can't get the \n newline characters onto the end of the lines. Am I missing something?
I want the output to look like:
This is line 1
This is line 2
This is line 3
Hello CD-RW,
Instead of invoking:
echo $FILE
try using:
echo -e $FILE
the -e option enables interpretation of backslash escapes....
If -e is in effect, the following sequences are recognized:
\0NNN the character whose ASCII code is NNN (octal)
\\ backslash
\a alert (BEL)
\b backspace
\c suppress trailing newline
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
Also consult man page for 'echo'....
Whatever may be the outcome.... please post your problem/soultion
-fav0nius
stevea
2nd July 2009, 08:53 AM
Yeah well - decent advice favOnious except "echo" is both a bash shell built-in AND a separate coreutils binary.
The" man echo" page only refers to the coreutils version. See "man bash" for the normally used version.
fav0nius
2nd July 2009, 09:41 AM
Ooh... it just skipped from my mind :D ...
Thanks for reminding :)
-fav0nius
CD-RW
2nd July 2009, 11:49 AM
Thanks for your replies and help fav0nius and stevea.
Here is the solution to my problem :)
[root@F10]# LINE1="This is line 1"
[root@F10]# LINE2="This is line 2"
[root@F10]# LINE3="This is line 3"
[root@F10]# FILE=${LINE1}'\n'${LINE2}'\n'${LINE3}
[root@F10]# echo -e $FILE
This is line 1
This is line 2
This is line 3
[root@F10]# echo -e $FILE > newfile.txt
[root@F10]# cat newfile.txt
This is line 1
This is line 2
This is line 3
So this will allow me to build a text file on-the-fly, directly from a bash script.
vBulletin® v3.8.7, Copyright ©2000-2013, vBulletin Solutions, Inc.