Skip to content
Advertisement

BASH / sed – not giving same output for simple sed commands

Box 1: uname -srm

JavaScript

Box 2: uname -srm; cat /etc/debian_version

JavaScript

BASH on box1 is: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)

BASH on box2 is: GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

On both boxes, I’m have the following script:

JavaScript

All commands are same. This is what I’m trying to do:

JavaScript

On box1: When I’m running the script with arguments: aa1, aa3,aa2 aa1 , a0, I’m getting the following output which is NOT what I’m expecting in the output (Character ‘n‘ is getting embedded here and it didn’t even do sort or uniq operation on the values):

JavaScript

On box2: When I’m doing the same: I’m getting the EXPECTED output.

JavaScript

What should I change so that the above expression gives same output on both machines? OR- do I have to update BASH on box1?

My understanding is, that I’m doing very simple sed operation and both BASH versions should have given me same output for such simple sed commands.

Advertisement

Answer

It seems a bit convoluted to add pipes, then remove them, then add them back again. This code works on macOS Sierra 10.12.1 (Darwin 16.1.0) — I believe it would work on Linux too:

JavaScript

The combination of setting IFS so it includes a comma and passing $args to printf without any quotes around it eliminates oddities in the spacing and commas. Sorting uniquely can be done in one operation. Then replace all the newlines with | symbols, then use sed to remove any leading or trailing |, add the leading ^ and trailing $ and the intermediate $|^ sequences. Then echo the result string.

When the script is made executable and called x37.sh, it produces:

JavaScript

There are ways to do without the tr command, making sed do the line concatenation.

Advertisement