我有一个以下格式的文本文件:
cat yourfile.txt
a
b
c
d
e
f
g
我想把它转换成:
a,b,c,d,e,f,g
这是我现在想到的解决方案:
while read line; do printf "%s%s" $line "," ; done < yourfile.txt
a,b,c,d,e,f,g,
两个问题:
- 我在结尾处多了一个逗号 (,)
- 我知道我可以在 shell 脚本中运行此命令并从我的 build.xml 中执行该 shell 脚本。或者有更优雅的解决方案?
最佳答案
你可以使用 sed
:
$ sed ':a;N;$!ba;s/\n/,/g' test.txt
a,b,c,d,e,f,g
参见 this answer阅读更多详情。
否则,对于其他解决方案,删除最后的逗号非常容易。例如 sed
:
$ cat test.txt|tr "\n" ","|sed "s/,$//g"
a,b,c,d,e,f,g
$ while read line; do printf "%s%s" $line "," ; done < test.txt|sed "s/,$//g" # with your solution
a,b,c,d,e,f,g
关于bash - 如何从 ant 脚本连接文件的所有行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21244518/