可变插补时的bash线串联 [英] bash line concatenation during variable interpolation

查看:133
本文介绍了可变插补时的bash线串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ cat isbndb.sample | wc -l
13
$ var=$(cat isbndb.sample); echo $var | wc -l
1

为什么换行符丢失时,我指定字符串变量?我怎样才能保持换行符被转换成空间?

Why is the newline character missing when I assign the string to the variable? How can I keep the newline character from being converted into a space?

我使用bash。

推荐答案

您必须引用变量preserve换行。

You have to quote the variable to preserve the newlines.

$ var=$(cat isbndb.sample); echo "$var" | wc -l

在两种情况下不必要的:

And cat is unnecessary in both cases:

$ wc -l < isbndb.sample
$ var=$(< isbndb.sample); echo "$var" | wc -l

编辑:

在其指定的内容给一个变量通常猛砸条从文件中额外的尾随换行。你必须采取一些技巧,以preserve他们。试试这个:

Bash normally strips extra trailing newlines from a file when it assigns its contents to a variable. You have to resort to some tricks to preserve them. Try this:

IFS='' read -d '' var < isbndb.sample; echo "$var" | wc -l

设置 IFS 为null $ P $从正对新行拆分和设置分隔符为null使它接受文件直到文件的末尾。

Setting IFS to null prevents the file from being split on the newlines and setting the delimiter for read to null makes it accept the file until the end of file.

这篇关于可变插补时的bash线串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆