为什么这个 sed 命令在 bash 脚本内什么都不做,但在外面工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/885798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does this sed command do nothing inside a bash script but work outside?
提问by Stuart Woodward
# 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.
上面的脚本来自 sourceforge 上的 sed one-liners 的大量列表。
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.
我希望在 bash 脚本中使用它,但如果在脚本中使用它则无效。如果我通过它通过管道传输脚本的输出,它会按照所述并排连接成对的行。
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.
某些字符必须需要转义,但我无法“看到”需要转义哪个字符才能使其在 bash 脚本中工作。
Yoroshiku Onegaishimasu!
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.
我在脚本中发现了破坏它的逻辑错误。
回答by brlcad
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.
如果您尝试将命令嵌入字符串或变量中,则 \n 将成为转义候选者。
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).
就其价值而言,除非您确实需要高级容器(这种情况很少见),否则很少有“强”案例可以直接通过 /bin/sh posix 兼容的 shell 脚本制作 bash 特定的脚本。您最终会得到一个脚本,该脚本对于许多其他与 posix/korn/bourne 兼容的 shell(包括 bash)具有更高的可移植性。
Cheers! Sean
干杯! 肖恩
回答by Jonathan Leffler
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.
对我有用 - 在 Cygwin 下。' al' 是一个程序,每行列出一个参数。
$ 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
$

