How do I replace a string with a newline using a bash script and sed?
30,863
Solution 1
This will work
sed 's/@@ /\n/g' filename
replaces @@
with new line
Solution 2
Using pure BASH string manipulation:
eol=$'\n'
line="${line//@@ /$eol}"
echo "$line"
Value1|Value2|Value3|Value4
Value5|Value6|Value7|Value8
Value9|etc...
Solution 3
I recommend using the tr function
echo "$line" | tr '@@' '\n'
For example:
[itzhaki@local ~]$ X="Value1|Value2|Value3|Value4@@ Value5|Value6|Value7|Value8@@"
[itzhaki@local ~]$ X=`echo "$X" | tr '@@' '\n'`
[itzhaki@local ~]$ echo "$X"
Value1|Value2|Value3|Value4
Value5|Value6|Value7|Value8
Solution 4
If you don't mind to use perl:
echo $line | perl -pe 's/@@/\n/g'
Value1|Value2|Value3|Value4
Value5|Value6|Value7|Value8
Value9|etc
Solution 5
Finally got it working with:
sed 's/@@ /'\\\n'/g'
Adding the single quotes around \\n seemed to help for whatever reason
Author by
Kevin Custer
Updated on July 10, 2020Comments
-
Kevin Custer almost 4 years
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 settingIFS='|'
to split up the values. If there is a better way please tell me, I am still a beginner with shell scripting. -
Kevin Custer almost 10 yearsSadly this did not work...it did not replace the "@@ " at all
line="${x//@@ /$eol}"
-
Kevin Custer almost 10 yearsThis did not work in my script, it still has the '@@ ' in the output:
echo $x | tr '@@ ' '\n' >> $OUTPUT
-
anubhava almost 10 years@odinsride: Make sure you use BASH. See with working demo: ideone.com/ePzOxq
-
itzhaki almost 10 yearsI know for a fact it works. I'm using "tr" all the time. Make sure you're using BASH and not SH, and that you're looking at the right output. Here, run this: pastebin.com/gxvKUwS9
-
Tripp Kinetics almost 10 yearsEdited answer to make solution compatible with performing operations on both rows and fields in those rows.
-
Tripp Kinetics almost 10 yearsAs far as I know, tr works on individual characters, not strings. As in,
tr 'Ab' 'aB'
turnsAbracadabra
intoaBracadaBra
. -
mitnk almost 10 yearsYou can replace
@@
to@
before usetr
:echo "1@@2@@3" | sed 's/@@/@/g' | tr '@' '\n'
-
prudviraj almost 10 years@rpax thanks for editing forgot to format my answer
-
rpax almost 10 yearsYou are welcome. Anyway, this is a good answer. I like it. +1
-
glenn jackman almost 10 yearsYou just need to "squeeze":
tr -s '@' '\n'
-
Benjamin W. over 5 yearsYou don't have to escape the first
@
, and this is missing a space after@@
. -
Benjamin W. over 5 yearsThe question asks to replace
@@
plus a blank, though.tr
can't do that.