shell 多行变量删除新行字符- Fish

l2osamch  于 2023-05-23  发布在  Shell
关注(0)|答案(4)|浏览(261)

当我在fish中将任何多行文本设置为变量时,它会删除新行字符并将其替换为空格,我如何才能阻止它这样做?最小完整示例:

~ ) set lines (cat .lorem); set start 2; set end 4;
~ ) cat .lorem 
once upon a midnight dreary while i pondered weak and weary
over many a quaint and curious volume of forgotten lore
while i nodded nearly napping suddenly there came a tapping
as of some one gently rapping rapping at my chamber door
tis some visiter i muttered tapping at my chamber door
~ ) cat .lorem | sed -ne $start\,{$end}p\;{$end}q  # Should print lines 2..4
over many a quaint and curious volume of forgotten lore
while i nodded nearly napping suddenly there came a tapping
as of some one gently rapping rapping at my chamber door
~ ) echo $lines
once upon a midnight dreary while i pondered weak and weary over many a quaint and curious volume of forgotten lore while i nodded nearly napping     suddenly there came a tapping as of some one gently rapping rapping at my chamber door tis some visiter i muttered tapping at my chamber door
k4aesqcs

k4aesqcs1#

fish在换行符上拆分命令替换。这意味着$lines是一个列表。你可以在这里阅读更多关于列表的信息。
当您将列表传递给命令时,列表中的每个条目都将成为一个单独的参数。echo用空格分隔其参数。这就解释了你看到的行为。
请注意,其他shell在这里做同样的事情。例如,在bash中:

lines=$(cat .lorem)
echo $lines

如果您想阻止拆分,您可以临时将IFS设置为空:

begin
   set -l IFS
   set lines (cat .lorem)
end
echo $lines

现在$lines将包含换行符。
正如faho所说,read也可以使用,并且稍微短一点:

read -z lines < ~/.lorem
echo $lines

但是考虑一下是否在换行符上进行拆分是您真正想要的。正如faho所暗示的,你的sed脚本可以用数组切片替换:

set lines (cat .lorem)
echo $lines[2..4] # prints lines 2 through 4
zed5wv10

zed5wv102#

从fish 3.4开始,我们可以使用"$(innercommand)"语法。

set lines "$(echo -e 'hi\nthere')"
set -S lines
# $lines: set in global scope, unexported, with 1 elements
# $lines[1]: |hi\nthere|
k3fezbri

k3fezbri3#

将其发送到string split0

set lines (echo -e 'hi\nthere')
set -S lines
# $lines: set in global scope, unexported, with 2 elements
# $lines[1]: length=2 value=|hi|
# $lines[2]: length=5 value=|there|

set lines (echo -e 'hi\nthere' | string split0)
set -S lines
# $lines: set in global scope, unexported, with 1 elements
# $lines[1]: length=9 value=|hi\nthere\n|

文件中指出:
如果输出作为最后一步通过管道传输到字符串split或字符串split0,则这些拆分将按其出现的形式使用,而不是拆分行。

gkl3eglg

gkl3eglg4#

这不仅仅是删除换行,而是在换行上进行分割。
变量$lines现在是一个列表,每行都是该列表中的一个元素。

set lines (cat .lorem)
for line in $lines
    echo $line
end
echo $lines[2]
printf "%s\n" $lines[2..4]

相关问题