Sylvester
Sylvester

Reputation: 27

Insert line break into a variable - Bash/Shell Script

I have a variable which contains output from a shell command, I'm trying to 'grep' the variable but it seems that the output is all in one line without linebreaks. So when I 'grep' the variable everything is returned.

For example my variable contains this:

 standalone 123 abc greefree ten1 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten1 stndalone 334 abc fregree ten2 

I'd like to insert a line break everywhere there is ten1 or ten2. So that when I 'grep' the variable I am only returned a particular line.

Output similar to this

standalone 123 abc greefree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2

Is there a bash command I can use or some type of regex expression?

Upvotes: 0

Views: 328

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133770

Could you please try following once.

sed 's/\r//g;s/ten[12]/&\n/g' Input_file

To remove spaces at last try(which will be remaining in above code):

sed -E 's/\r//g;s/ten[12]/&\n/g'  Input_file | sed -E 's/^ +//'

To edit based on multiple patterns

sed -e 's/\r//g;s/ten[12]/&\n/g' -e 's/\r//g;s/abc[12]/&\n/g' Input_file

Upvotes: 1

Mark
Mark

Reputation: 4453

Here's a combination of sed and tr that might get you closer to what you want:

sed -e 's/ten1/^M/g' -e 's/ten2/^M/g' | tr \\r \\n

So, let's say you have a variable called LONG, you can use the above code as follows:

echo "$LONG" | sed -e 's/ten1/^M/g' -e 's/ten2/^M/g' | tr \\r \\n

Above, we are converting all of the ten1 and ten2 strings to CR (carriage return) and then we are using tr to change those CR's into newlines. Put your grep in after statement:

echo "$LONG" | sed -e 's/ten1/^M/g' -e 's/ten2/^M/g' | tr \\r \\n | grep whatever

After re-reading your question and the other answer, I am providing this bit of code to also include the original ten1 or ten2:

 echo "$LONG" | sed 's/ten[12] /&^M/g'  | tr \\r \\n

And this is the output:

standalone 123 abc greefree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten1 
stndalone 334 abc fregree ten2

Upvotes: 1

Related Questions