Linux echo on one line

echo a file as a single line with \n’s

I have a multi line text file that I want to echo out as a single line file where the new lines are shown as \n. Any pointers would be great.

4 Answers 4

Using the Perl sledgehammer:

The echo is there to print a trailing newline just in case it’s wanted for display purposes. This changes the NL on the last line to \n too.

Or a rather straightforward solution in just Bash, assuming the file doesn’t contain any embedded NUL bytes. Though note that this loads the whole file in memory:

you can avoid the echo using perl -pe ‘s/\n/\\n/; END‘ or if last \n is not needed, perl -pe ‘s/\n/\\n/ if !eof’

Beware of a few special cases you may need to consider here. Let’s take as example 4 files:

  • file1 an empty file
  • file2 a file with a single newline (␤) character (one empty line)
  • file3 a proper text file like:

(for instance so that you can reconstruct the file by passing the output to printf %b ).

You can adapt if you want to ignore the delimiter of the last line if any, or don’t want the trailing newline, but then you may want to test on those 4 different cases that it does what you want as you’ll probably find that you need to have special treatments for some of them.

solution to ignore the delimiter of the last line produces one empty line for both file1 and file2 (and for not-properly-delimited text ( file4 ) may not work properly with all sed / paste implementations as those are meant to deal with valid text).

may be more portable, and maybe slightly better for file1 and file2 which it would leave untouched.

Источник

How to Use echo Command Without Newline

Every time you use echo, it adds a newline character at the end. Here’s what you can do if you want to use echo without newline.

The echo command is a handy way of printing anything in shell scripts.

By default, it always adds a new line character. So if you run multiple echo commands, each output is displayed on a new line.

But this could be inconvenient in situations where you need to print with echo command but without the newline.

Imagine yourself trying to print the Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55

You can use the -n flag of the echo command to print without newline:

You’ll notice that the prompt is displayed in the same line immediately after the Hello World now.

echo command without new line

Let’s take a more in-depth look at it.

Printing echo command without new line

Let’s take a simple for loop that prints the contents of an array in bash script and check it’s output.

$ bash_array=(1 2 3 4) $ for i in $; do echo $i done 1 2 3 4

As you can see, each time the echo command is executed, the output is displayed on a newline. Sometimes that is what you want, other times, you want the output to continue on the same line without starting on the newline.

Meet the «-n» flag

The bash implementation of the echo command usually appends a «\n» (an escape character to signify a newline) to the output. The «-n» flag does not append a «\n» to the output.

$ bash_array=(1 2 3 4 5 6 7 8) $ for i in $; do echo -n $i done 12345678

As you can see, all the numbers are now displayed in a single line. This means each time that the echo command was run, it did not output to a newline.

echo -n didn’t work. Now what?

In some cases, using echo -n also prints the -n character instead of printing the text without newline.

That’s possible if there is a separate implementation of the echo command by the shell you are using.

Confused? Some distributions and shells may have their own implementation of some built-in shell commands. echo is one such command.

Here are a few things you may try.

Add the shebang character followed by /bin/bash to ensure that your shell script uses bash shell.

If that doesn’t work, you may try using the printf command instead of echo.

By default, printf doesn’t add the newline character:

printf "Something without newline"

You have to explicitly provide the newline character \n:

printf "Something with newline\n"

The printf command behaves like the printf command in C and you can use it to print more complicated formatted outputs.

The printf command has much more consistent behavior. echo is fine for simple things, but I advise using printf for anything more complicated.

I hope this simple tutorial helps you in controlling the behavior of new line in bash scripts.

Источник

Echo Output on the Same line [duplicate]

I am trying get a output printed on a same line using echo command in bash script. Echo Command is given inside a loop, everytime the loop runs, executes a echo command. But normally, echo will take a new line everytime it executes, but I want the output to be on the same line everytime it executes. This is how my sample small code look:

 #!/bin/bash loop=1; while [ $loop -lt 5 ]; do echo "-" let loop=loop+1 done 

I also tried with -n option of echo command, but I got no output. I replaced the stmt — echo «-» with echo -n «-«. Desired output is: «——» Can some one help me on this

I am beginner to shell. ‘Powershell’ also appeared as a suggestions to the tags. I don really know the difference between the shell and powershell.

You can always hover over the tags and it will give you a description. I removed the tag and added bash so the right people will find your question.

3 Answers 3

which should have worked. In fact, I suspect that it did.

The problem may be that you don’t have a newline at the very end of your output. With the change to

your script should print 5 — characters with no newline. The output may have been clobbered by the shell prompt printed after your script finishes.

As a quick test, try adding

to the end of your script and see if the —— appears. After 5 seconds, see what happens when your next shell prompt is printed.

#!/bin/bash loop=1; while [ $loop -lt 5 ] do echo -n "-" let loop=loop+1 done echo "" 

The final echo «» prints just a newline.

Some other things to note:

Indentation is important, especially for larger and more complex scripts. It shows the structure of your code at a glance and makes it much easier to read.

In the code in your question, you have a space in front of the #!/bin/bash . The #! is recognized only at the very beginning of the line. Without a valid #! line, your script will be executed by /bin/sh , not by /bin/bash . It probably doesn’t matter in this case, since you’re not using any bash-specific features. It may have been an error introduced when you posted the question, but be sure to check your actual script and remove the space if it’s there.

The echo command exists in a number of different versions. It’s built into most shells, and also available as a separate executable /bin/echo . The different versions can have subtly different behavior in which options they recognize and the syntax of special characters. Support for the -n option to print a line with no terminating newline is probably almost universal.

The printf command (similar to C’s printf() function) also exists in multiple implementations, but its behavior is much more consistent. It’s safer to use printf rather than echo if you’re doing anything more than printing a simple one-line message. Again, it probably won’t matter in this case, but it’s a good thing to keep in mind.

Источник

How to show and update echo on same line

But I wish to make it so the «echo» shows the following echo on the next line (Not concatenate with the last echo output but replace it) so to make it look like it is updating. Similar to how a progress bar with percent would show on the same line.

7 Answers 7

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e .

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r . Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r 

I had to escape the escape symbol so bash would not kill it. That is why you see 2 \ symbols above.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

Just a note for the future: printf will do exactly the same thing, without any options. The advantage is printf generally behaves similarly in every environment and OS, while echo can sometimes behave very differently. For cross-platform scripts (or if you think you may ever care about that), using printf is best-practice.

printf a; printf b outputs ab — printf a\\r; printf b outputs b — printf a\\r; sleep 1; printf b outputs a , then b

The simple fix for the quoting is to put the \r inside the double quotes, too. But generally, like others already commented, avoid echo -e in favor of printf .

If I have understood well, you can get it replacing your echo with the following line:

echo -ne "Movie $movies - $dir ADDED! \033[0K\r" 

Here is a small example that you can run to understand its behaviour:

#!/bin/bash for pc in $(seq 1 100); do echo -ne "$pc%\033[0K\r" sleep 1 done echo 

The rest of answers are pretty good, but just wanted to add some extra information in case someone comes here looking for a solution to replace/update a multiline echo.

So I would like to share an example with you all. The following script was tried on a CentOS system and uses «timedatectl» command which basically prints some detailed time information of your system.

I decided to use that command as its output contains multiple lines and works perfectly for the example below:

#!/bin/bash while true; do COMMAND=$(timedatectl) #Save command result in a var. echo "$COMMAND" #Print command result, including new lines. sleep 3 #Keep above's output on screen during 3 seconds before clearing it #Following code clears previously printed lines LINES=$(echo "$COMMAND" | wc -l) #Calculate number of lines for the output previously printed for (( i=1; i  

The above will print the result of " timedatectl " forever and will replace the previous echo with updated results.

I have to mention that this code is only an example, but maybe not the best solution for you depending on your needs. A similar command that would do almost the same (at least visually) is " watch -n 3 timedatectl ".

But that's a different story. 🙂

Источник

Print one file per line using echo

How can I print a list of files/directories one-per-line using echo ? I can replace spaces with newlines, but this doesn't work if the filenames contain spaces:

$ echo small*jpg small1.jpg small2.jpg small photo 1.jpg small photo 2.jpg $ echo small*jpg | tr ' ' '\n' small1.jpg small2.jpg small photo 1.jpg small photo 2.jpg 

2 Answers 2

echo can't be used to output arbitrary data anyway, use printf instead which is the POSIX replacement for the broken echo utility to output text.

to output the list in NUL delimited records (so it can be post-processed; for instance using GNU xargs -r0 ; remember that the newline character is as valid as space or any character in a filename).

Before POSIX came up with printf , ksh already had a print utility to replace echo . zsh copied it and added a -l option to print the arguments one per line:

ksh93 added a -f option to print for printf like printing. Copied by zsh as well, but not other ksh implementations:

Note that all of those still print an empty line if not given any argument. A better println can be written as a function as:

echo only uses spaces to separate the strings it receives as arguments.

Since your question is tagged bash, here is what help echo in bash says (emphasis mine):

Display the ARGs, separated by a single space character and followed by a newline, on the standard output.

Similar statements are found in the documentation for other implementations. E.g. that of echo from coreutils , which you would likely find on GNU/Linux:

echo writes each given string to standard output, with a space between each and a newline after the last one.

If you really want echo to print your file names on separate lines you have to feed them as a single string:

$ touch "small1.jpg" "small2.jpg" "small photo 1.jpg" "small photo 2.jpg" $ (set -- small*.jpg; IFS=' '; echo "$*") small1.jpg small2.jpg small photo 1.jpg small photo 2.jpg 

Here we are leveraging the behavior of the * special parameter: within double-quotes it expands to a single word in which the elements of the array of positional parameters are concatenated using the first character of the IFS variable (which we set to a newline).

The (. ) syntax is used to execute the commands in a subshell environment—we generally don't want to affect the main one.

Note, however, that all echo 's limitations still apply, as mentioned in Stéphane's answer, and therefore its use in this scenario is not advisable.

Источник

Читайте также:  X96 mini linux install
Оцените статью
Adblock
detector