How to replace string with new string using 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 "@@" with a new line. I tried different things with sed, but I had no luck:

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

Ultimately, I need to parse all this input into strings and values. Maybe I'm wrong. I planned to replace "@@" with new lines and then scroll through the input with IFS = '|' to separate values. If there is a better way, tell me, I'm still starting with shell scripts.

Thanks!

+8
unix bash shell sed
source share
7 answers

hope it works

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

replaces @@ new line

+8
source share

Using pure BASH string manipulation:

 eol=$'\n' line="${line//@@ /$eol}" echo "$line" Value1|Value2|Value3|Value4 Value5|Value6|Value7|Value8 Value9|etc... 
+3
source share

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 
+3
source share

If you don't mind using perl:

 echo $line | perl -pe 's/@@/\n/g' Value1|Value2|Value3|Value4 Value5|Value6|Value7|Value8 Value9|etc 
+2
source share

What about:

 for line in `echo $longline | sed 's/@@/\n/g'` ; do $operation1 $line $operation2 $line ... $operationN $line for field in `echo $each | sed 's/|/\n/g'` ; do $operationF1 $field $operationF2 $field ... $operationFN $field done done 
+1
source share

Finally, he worked with:

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

Adding single quotes around \\ n seemed to help for some reason

+1
source share

This completes using perl to do this, and gives some simple help.

 $ echo "hi\nthere" hi there $ echo "hi\nthere" | replace_string.sh e hi th re $ echo "hi\nthere" | replace_string.sh hi there $ echo "hi\nthere" | replace_string.sh hi bye bye there $ echo "hi\nthere" | replace_string.sh e super all hi thsuperrsuper 

replace_string.sh

 #!/bin/bash ME=$(basename $0) function show_help() { IT=$(CAT <<EOF replaces a string with a new line, or any other string, first occurrence by default, globally if "all" passed in usage: $ME SEARCH_FOR {REPLACE_WITH} {ALL} eg $ME : -> replaces first instance of ":" with a new line $ME : b -> replaces first instance of ":" with "b" $ME ab all -> replaces ALL instances of "a" with "b" ) echo "$IT" exit } if [ "$1" == "help" ] then show_help fi if [ -z "$1" ] then show_help fi STRING=$1 TIMES=${3:-""} WITH=${2:-"\n"} if [ "$TIMES" == "all" ] then TIMES="g" else TIMES="" fi perl -pe "s/$STRING/$WITH/$TIMES" 
0
source share

All Articles