替代cut命令的--output-delimiter选项

11

我创建了一个使用的脚本

cut -d',' -f- --output-delimiter=$'\n'

要在RHEL 5中为每个命令分隔值添加换行符,例如:

[root]# var="hi,hello how,are you,doing"
[root]# echo $var
hi,hello how,are you,doing
[root]# echo $var|cut -d',' -f- --output-delimiter=$'\n'
hi
hello how
are you
doing

但不幸的是,当我在Solaris 10中运行相同的命令时,它根本不起作用 :( !

bash-3.00# var="hi,hello how,are you,doing"
bash-3.00# echo $var
hi,hello how,are you,doing
bash-3.00# echo $var|cut -d',' -f- --output-delimiter=$'\n'
cut: illegal option -- output-delimiter=

usage: cut -b list [-n] [filename ...]
       cut -c list [filename ...]
       cut -f list [-d delim] [-s] [filename]

我查看了“cut”命令的手册,但不幸的是里面没有“--output-delimiter”选项!

那么在Solaris 10(bash)中该怎么做呢?我猜awk可能是一个解决方案,但我无法正确地组合选项。

注意:逗号分隔的变量中可能包含空格。


如果你想要在RHEL上使用相同的cut命令,那么请安装GNU coreutils软件包。 - alanc
2个回答

9

使用tr怎么样?

$ tr ',' '\n' <<< "$var"
hi
hello how
are you
doing

或者

$ echo $var | tr ',' '\n'
hi
hello how
are you
doing

使用

$ sed 's/,/\n/g' <<< "$var"
hi
hello how
are you
doing

或者使用

$ awk '1' RS=, <<< "$var"
hi
hello how
are you
doing

1
我感觉自己像个大笨蛋!!!我从没想过使用'tr'或'sed'...噗......非常感谢你的答案! - Marcos
'sed' 没有起作用,bash-3.00# echo $var|sed -e 's/,/\n/g' hinhello hownare youndoing但是 'tr' 起作用了! - Marcos
嗯,我没有Solaris服务器进行测试,但也许在https://dev59.com/WGox5IYBdhLWcg3ww28D中你可以找到一些线索。很高兴看到`tr`对你来说是好的 :) - fedorqui

3
也许可以在本身中完成?
var="hi,hello how,are you,doing"
printf "$var" | (IFS=, read -r -a arr; printf "%s\n" "${arr[@]}")
hi
hello how
are you
doing

谢谢您的回答,但我更喜欢更小的东西,而且我不想使用数组来实现。 - Marcos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接