使用 sed 用分隔符分割字符串 [英] Using sed to split a string with a delimiter

查看:106
本文介绍了使用 sed 用分隔符分割字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下格式的字符串:

I have a string in the following format:

string1:string2:string3:string4:string5

我正在尝试使用 sed 拆分 : 上的字符串并将每个子字符串打印在新行上.这是我正在做的:

I'm trying to use sed to split the string on : and print each sub-string on a new line. Here is what I'm doing:

cat ~/Desktop/myfile.txt |sed s/:/\n/

打印:

string1
string2:string3:string4:string5

我怎样才能让它在每个分隔符上拆分?

How can I get it to split on each delimiter?

推荐答案

要使用 GNU sed 使用分隔符拆分字符串,您说:

To split a string with a delimiter with GNU sed you say:

sed 's/delimiter/
/g'     # GNU sed

例如,使用 : 作为分隔符进行拆分:

For example, to split using : as a delimiter:

$ sed 's/:/
/g' <<< "he:llo:you"
he
llo
you

或者使用非 GNU sed:

Or with a non-GNU sed:

$ sed $'s/:/\
/g' <<< "he:llo:you"
he
llo
you

<小时>

在这种特殊情况下,您错过了替换后的 g.因此,它只完成一次.见:


In this particular case, you missed the g after the substitution. Hence, it is just done once. See:

$ echo "string1:string2:string3:string4:string5" | sed s/:/\n/g
string1
string2
string3
string4
string5

g 代表 global,意味着替换必须在全局范围内完成,也就是说,对于任何出现.看到默认是1,如果你把例子2,它做了2次,等等.

g stands for global and means that the substitution has to be done globally, that is, for any occurrence. See that the default is 1 and if you put for example 2, it is done 2 times, etc.

在您的情况下,您需要使用:

All together, in your case you would need to use:

sed 's/:/\n/g' ~/Desktop/myfile.txt

请注意,您可以直接使用 sed ... file 语法,而不是不必要的管道: cat file |sed.

Note that you can directly use the sed ... file syntax, instead of unnecessary piping: cat file | sed.

这篇关于使用 sed 用分隔符分割字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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