bash 如何将行连接成一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10303600/
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
how to concatenate lines into one string
提问by Shep
I have a function in bash that outputs a bunch of lines to stdout. I want to combine them into a single line with some delimiter between them.
我在 bash 中有一个函数可以将一堆行输出到标准输出。我想将它们组合成一行,它们之间有一些分隔符。
Before:
前:
one
two
three
After:
后:
one:two:three
What is an easy way to do this?
有什么简单的方法可以做到这一点?
回答by abecadel
And another way:
而另一种方式:
cat file | tr -s "\n" ":"
回答by potong
This might work for you:
这可能对你有用:
paste -sd':' file
回答by shellter
Taking @glennHymanman's corrections verbatim
逐字记录@glennHymanman 的更正
awk '{printf("%s%s", sep, while read line ; do printf "%s:" $line ; done < file | sed s'/:$//'
); sep=":"} END {print ""}' file
Or as you specified bash
或者按照您指定的 bash
echo $'one\n2 and 3\nfour' | { mapfile -t lines; IFS=:; echo "${lines[*]}"; }
I hope this helps
我希望这有帮助
回答by glenn Hymanman
For fun, here's a bash-only way:
为了好玩,这里有一个 bash-only 方式:
one:2 and 3:four
outputs
输出
one
two
three
The {}grouping is to ensure all the commands that refer to the array variable are executed in the same subshell. The variable will not exist once the pipeline ends.
的{}分组是要确保所有引用数组变量在同一子shell被执行的命令。一旦管道结束,该变量将不存在。
http://www.gnu.org/software/bash/manual/bashref.html#index-mapfile-140
http://www.gnu.org/software/bash/manual/bashref.html#index-mapfile-140
回答by Debaditya
Input.txt
输入.txt
one two three
@a = `cat /home/Input.txt`; foreach my $x (@a) { chomp($x); push(@array,"$x"); } chomp(@array); print "@array";
Perl Solution : dummy.pl
Perl 解决方案:dummy.pl
##代码##Run the script as :
运行脚本:
$> perl dummy.pl | sed 's/ /:/g' > Output.txt
$> perl dummy.pl | sed 's/ /:/g' > 输出.txt
Output.txt
输出.txt
one:two:three
一二三

