Fadi
Fadi

Reputation: 1419

Bash - one-liner echo with delimiter

So my sample code so far looks like this:

#!/bin/bash

mysampletxt="=======\nTest\n-------;----------\nDone Test\n=========="

I want to be able to echo it out to make it look like the following:

=======
Test
-------
Some code goes here
More code
----------
Done Test
==========

But the problem is that when I tried using AWK, sed, or IFS they also use \n as delimiters which I don't want that to happen as the text gets all messed up. Is there anyway I can include ; as the delimiter and ignore \n?

I was looking at this. But unfortunately none of those solutions worked for me.

Any help would be greatly appreciated!

EDIT: For more clarification: I'm trying to do is split mysampletxt into two from the ; character.. And be able to insert the first part of the split text one place and the second into another.

Upvotes: 0

Views: 9396

Answers (3)

Cyrus
Cyrus

Reputation: 88654

echo -e "${mysampletxt%;*}\nSome code goes here\nMore code\n${mysampletxt#*;}"

or

printf "%b" "${mysampletxt%;*}\nSome code goes here\nMore code\n${mysampletxt#*;}"

Upvotes: 4

a p
a p

Reputation: 3208

If you can use something other than awk or sed (maybe overkill):

[ap@localhost ~]$ perl -e 'print "===\n\n---\n\n;"'
===

---

;[ap@localhost ~]$python -c "print ' ====\n====\n;'"
 ====
====
;

Upvotes: 0

John1024
John1024

Reputation: 113864

Another option is to define your string with $'...':

$ mysampletxt=$'=======\nTest\n-------;\n----------\nDone Test\n=========='
$ echo "$mysampletxt"
=======
Test
-------;
----------
Done Test
==========

To do the substitution also:

$ echo "${mysampletxt/;/$'\nSome code goes here\nMore code'}"
=======
Test
-------
Some code goes here
More code
----------
Done Test
==========

Upvotes: 1

Related Questions