如何分割用逗号没有空格名单 [英] How to split a list by comma not space

查看:147
本文介绍了如何分割用逗号没有空格名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要拆与逗号文本不是空间 中富列表。假设我有一个CSV文件 CSV_File 里面坐了以下文字:

I want to split a text with comma , not space in for foo in list. Suppose I have a CSV file CSV_File with following text inside it:

Hello,World,Questions,Answers,bash shell,script
...

我用下面的code将其分割成几个单词:

I used following code to split it into several words:

for word in $(cat CSV_File | sed -n 1'p' | tr ',' '\n')
do echo $word
done

它打印:

Hello
World
Questions
Answers
bash
shell
script

但我想它分裂用逗号文本没有空格:

But I want it to split the text by commas not spaces:

Hello
World
Questions
Answers
bash shell
script

我怎么能在bash做到这一点?

How can I achieve this in bash?

推荐答案

使用子shell替换来分析的话撤销所有你正在做把空间一起工作。

Using a subshell substitution to parse the words undoes all the work you are doing to put spaces together.

而不是尝试:

cat CSV_file | sed -n 1'p' | tr ',' '\n' | while read word; do
    echo $word
done

这也增加了并行性。使用子shell作为你的问题迫使整个子shell进程完成之前,你可以重头再来的答案迭代。管道连接到子shell(在我的答案),让他们可以并行工作。这一点很重要,如果只有你当然有文件中的许多行。

That also increases parallelism. Using a subshell as in your question forces the entire subshell process to finish before you can start iterating over the answers. Piping to a subshell (as in my answer) lets them work in parallel. This matters only if you have many lines in the file, of course.

这篇关于如何分割用逗号没有空格名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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