bash 使用 shell 脚本将逗号分隔值转换为值列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31071432/
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
convert comma separated values into a list of values using shell script
提问by Prashanth
I have csv data like:
我有 csv 数据,如:
a,b,c,d,e,f,g,h
I want this data in a list, one letter in each line. Is it possible is shell script? I have tried to extract each letter using cut command as shown below:
我希望将这些数据放在一个列表中,每行一个字母。有可能是shell脚本吗?我尝试使用 cut 命令提取每个字母,如下所示:
less list.txt | cut -d"," -f?
The command is working but the problem here is the number of fields is unknown. I have to place this command in a loop and iterate on the list so that I can extract the values one-by-one a redirect them to another file.
该命令正在运行,但这里的问题是字段数未知。我必须将这个命令放在一个循环中并在列表上迭代,以便我可以一个一个地提取值并将它们重定向到另一个文件。
回答by Joe
Use tr
to change ,
into newlines:
使用tr
来改变,
到新行:
tr , "\n" < list.txt
回答by jhoepken
You can use sed
for this:
您可以sed
为此使用:
sed "s/,/\n/g" list.txt
Output
输出
a
b
c
d
e
f
回答by fedorqui 'SO stop harming'
Yes, you can use cut
. The key point is the usage of --output-delimiter
. If you set it as new line, everything works:
是的,您可以使用cut
. 关键是使用--output-delimiter
. 如果将其设置为新行,则一切正常:
cut -d',' --output-delimiter=$'\n' -f1- file
Note also two facts:
还要注意两个事实:
- we use
-f1-
to print from the first field up to the last one. Then-
syntax means: from the n-th field up to the end. - we use
$'\n'
because\n
alone would print literal\n
instead of real new lines.
- 我们使用
-f1-
从第一个字段打印到最后一个字段。的n-
语法的装置:从第n场到最后。 - 我们使用
$'\n'
因为\n
单独打印文字\n
而不是真正的新行。
Test
测试
$ echo "a,b,c,d,e,f,g,h" | cut -d',' --output-delimiter=$'\n' -f1-
a
b
c
d
e
f
g
h
From man cut
:
来自man cut
:
--output-delimiter=STRING
use STRING as the output delimiter the default is to use the input delimiter
--output-delimiter=STRING
使用 STRING 作为输出分隔符默认是使用输入分隔符
回答by Alek
You could use the tr
command to transform each "," into a newline.
您可以使用该tr
命令将每个“,”转换为换行符。
cat list.txt | tr "," "\n"
From then you can output each line wherever you want using a while read loop
从那时起,您可以使用 while 读取循环将每一行输出到您想要的任何位置
cat list.txt | tr "," "\n" | while read LINE
do
echo "$LINE" >> ~/wherever/you/want
done
Or ...
或者 ...
while read LINE
do
echo "$LINE" >> ~/wherever/you/want
done <<< "$(cat list.txt | tr "," "\n")"
Either works.
要么有效。