如何在 Bash 中连接文件中的所有行?
我有一个文件 csv
:
data1,data2,data2
data3,data4,data5
data6,data7,data8
我想将其转换为(包含在变量中):
variable
=data1,data2,data2%0D%0Adata3,data4, data5%0D%0Adata6,data7,data8
我的尝试:
data=''
cat csv | while read line
do
data="${data}%0D%0A${line}"
done
echo $data # Fails, since data remains empty (loop emulates a sub-shell and looses data)
请帮助..
I have a file csv
:
data1,data2,data2
data3,data4,data5
data6,data7,data8
I want to convert it to (Contained in a variable):
variable
=data1,data2,data2%0D%0Adata3,data4,data5%0D%0Adata6,data7,data8
My attempt :
data=''
cat csv | while read line
do
data="${data}%0D%0A${line}"
done
echo $data # Fails, since data remains empty (loop emulates a sub-shell and looses data)
Please help..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
从文件中删除换行符更简单:
Simpler to just strip newlines from the file:
在 bash 中,
在非 bash shell 中,您可以使用
`...`
代替$(...)
。另外,echo -n
可以抑制换行符,不幸的是它并不完全可移植,但同样可以在 bash 中使用。In bash,
In non-bash shells, you can use
`...`
instead of$(...)
. Also,echo -n
, which suppresses the newline, is unfortunately not completely portable, but again this will work in bash.其中一些答案非常复杂。这个怎么样。
或者
对你来说太“外部实用”?
现在你有了一个数组!随心所欲地输出它,也许
仍然太“外部效用?”好吧,
是的,
printf
可以是内置函数。如果不是,但您的echo
是并且它支持-n
,请改用echo -n
:好的,现在我承认我是变得有点傻了。安德鲁的回答是完全正确的。
Some of these answers are incredibly complicated. How about this.
or
Too "external utility" for you?
Now you have an array! Output it however you like, perhaps with
Still too "external utility?" Well fine,
Yes,
printf
can be a builtin. If it isn't but yourecho
is and it supports-n
, useecho -n
instead:Okay, now I admit that I am getting a bit silly. Andrew's answer is perfectly correct.
我更喜欢循环:
注意:此解决方案要求输入文件在文件末尾有一个新行,否则它将删除最后一行。
I would much prefer a loop:
Note: This solution requires the input file to have a new line at the end of the file or it will drop the last line.
另一个简短的 bash 解决方案
Another short bash solution
使用 shell:
最近的 bash 版本:
With shell:
Recent bash versions:
一个非常简单的单行解决方案,不需要额外的文件,因为它很容易理解(我认为,只需将文件放在一起并执行 sed-replace ):
A very simple single-line solution which requires no extra files as its quite easy to understand (I think, just cat the file together and perform sed-replace):
没用的猫,受罚!您想要将 CSV 送入循环
Useless use of cat, punished! You want to feed the CSV into the loop