Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace a string with a newline using a bash script and sed?

I have the following input:

Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@ Value9|etc...

In my bash script I would like to replace the @@ with a newline. I have tried various things with sed but I'm not having any luck:

line=$(echo ${x} | sed -e $'s/@@ /\\\n/g')

Ultimately I need to parse this whole input into rows and values. Maybe I am going about it wrong. I was planning to replace the @@ with newlines and then loop through the input with setting IFS='|' to split up the values. If there is a better way please tell me, I am still a beginner with shell scripting.

like image 569
Kevin Custer Avatar asked May 07 '14 15:05

Kevin Custer


People also ask

How do you use sed to substitute a new line?

Using `sed` to replace \n with a comma By default, every line ends with \n when creating a file. The `sed` command can easily split on \n and replace the newline with any character. Another delimiter can be used in place of \n, but only when GNU sed is used.

How do I add a new line to a string in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way. However, it's also possible to denote newlines using the “$” sign.

How do I replace a line in a bash script?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

This will work

sed 's/@@ /\n/g' filename

replaces @@ with new line

like image 65
prudviraj Avatar answered Sep 28 '22 06:09

prudviraj