views:

853

answers:

2
 # join pairs of lines side-by-side (like "paste")
 sed '$!N;s/\n/ /'

The above script comes from the great list of sed one-liners found on sourceforge.

I wish to use it in an a bash script but it has no effect if used inside the script. If I pipe the output of the script through it, it joins join pairs of lines side-by-side as described.

Some character must need escaping but I just can't "see" which character needs to be escaped to make it work inside a bash script.

Yoroshiku Onegaishimasu!

Later..

#!/bin/bash
# numbers.sh

for X in 1 2 3 4 5 6 7 8 9 0
do
        echo $X
done

When used this script:

#!/bin/bash

./numbers.sh | sed '$!N;s/\n/ /'

works fine..

1 2
3 4
5 6
7 8
9 0

Please let me regroup my thoughts on this..

Later...

I found the logical error in the script which broke it.

+2  A: 

It's not obvious to me what the problem is without seeing your script. A quick test here and it worked just fine inside of a simple script:

#!/bin/bash
cat /etc/crontab | sed '$!N;s/\n/ /'

If you're trying to embed the command inside a string or variable, the \n will be an escape candidate.

For what it's worth, there's rarely a 'strong' case for making bash-specific scripts over straight up /bin/sh posix-compliant shell scripts unless you really need the advanced containers (which is rare). You'll end up with a script that is considerably more portable to dozens of other posix/korn/bourne-compatible shells (including bash).

Cheers! Sean

brlcad
Thanks for the comment, I had no reason to use bash and I have now confirmed that, as you say, it works fine. It must be something more specific to the script itself.
Stuart Woodward
+1  A: 

Are you missing the "$@" to indicate the file name arguments - so it was only reading from standard input?

What was the misbehaviour? Was the file simply copied to standard output?

Works for me - under Cygwin. 'al' is a program that lists its arguments one per line.

$ al a b c d e f  | sed '$!N;s/\n/ /'
a b
c d
e f
$ cat xxx
sed '$!N;s/\n/ /'
$ al a b c d e f g | bash xxx
a b
c d
e f
g
$
Jonathan Leffler
The bad behaviour was that the output was not changed at all by the sed command when inside the script.I have now verified, in the simplest case it works as expected and is not a matter of escaping. Thanks for your help!
Stuart Woodward