当我将任何多行文本设置为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
~ ) echo $lines | sed -ne $start\,{$end}p\;{$end}q # Should print lines 2..4
~ ) cat .lorem | sed -ne $start\,{$end}p\;{$end}q
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
答案 0 :(得分:5)
fish在换行符上拆分命令替换。这意味着$lines
是一个列表。您可以阅读更多about lists here。
将列表传递给命令时,列表中的每个条目都成为单独的参数。 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
答案 1 :(得分:0)
这不仅仅是删除换行符,而是拆分换行符。
您的变量$ lines现在是一个列表,每行都是该列表中的一个元素。
见
set lines (cat .lorem)
for line in $lines
echo $line
end
echo $lines[2]
printf "%s\n" $lines[2..4]