How do I split a String and keep the delimiters?

How can I split a long text string with "\n" with simple shell/bash commands, and then write it to a file?

  • The objective is using only bash/ash syntax and very simple commands ( no sed/awk ). The scenario is the following, we have a long text in a shell variable with "\n" delimiters, like the one generated by the following loop: #!/bin/sh messages="" for index in $(seq 1 "${1}"); do messages="${messages}\n""trial ${index}" done Now if i redirect this variable to a text file with echo, i get an error ( The maximum length of arguments for a new process ), this can be replicated by: /bin/echo -e "${lmessages}" >> /tmp/test.log when ${1} is greater than 40'000 . So, how can i write this large text variable to a file, splitting in in the process, without hitting the limit of "max arguments"? This, if possible, avoiding awk/sed (why? Because i would like to solve it without using other common turing complete interpreters) and arrays. Update1 To be clearer in what i mean, example with a string LITERAL that contains simple "\n" identifier, while my problem involves a variable! (because if i try to echo the variable, i get an error due to the text too large to be passed as an argument) root@meh# echo "bla\nbla" | while read -r line; do echo $line; done -- output bla\nbla I want root@meh# echo "bla\nbla" | <some code> -- output bla bla endUpdate sister question: http://unix.stackexchange.com/questions/148357/write-variable-containing-large-text-with-n-to-a-file-with-common-shell-interpr

  • Answer:

    I'm not 100% sure I understand what you ask but you could try something like while read -r line; do echo $line foo done $ cat long.txt a b sdkfjalsjfk skfjalksfjd d $ ./test.sh < long.txt a foo b foo sdkfjalsjfk skfjalksfjd foo d foo Or something similar. This will read the input (which can be a variable just as well) line by line.

Marko Poutiainen at Quora Visit the source

Was this solution helpful to you?

Other answers

Are you looking for echo -e? sh-3.2$  echo -e "bla\nbla" | while read -r line; do echo $line; done bla bla

Reshmi VS

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.