Linux 使用 sed 用分隔符分割字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18234378/
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
Using sed to split a string with a delimiter
提问by hax0r_n_code
I have a string in the following format:
我有以下格式的字符串:
string1:string2:string3:string4:string5
string1:string2:string3:string4:string5
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:
我正在尝试使用sed
拆分字符串:
并将每个子字符串打印在新行上。这是我在做什么:
cat ~/Desktop/myfile.txt | sed s/:/\\n/
cat ~/Desktop/myfile.txt | sed s/:/\\n/
This prints:
这打印:
string1
string2:string3:string4:string5
How can I get it to split on each delimiter?
我怎样才能让它在每个分隔符上拆分?
采纳答案by fedorqui 'SO stop harming'
To split a string with a delimiter with GNU sed you say:
要使用 GNU sed 用分隔符分割字符串,您可以说:
sed 's/delimiter/\n/g' # GNU sed
For example, to split using :
as a delimiter:
例如,要使用:
作为分隔符进行拆分:
$ sed 's/:/\n/g' <<< "he:llo:you"
he
llo
you
Or with a non-GNU sed:
或者使用非 GNU sed:
$ sed $'s/:/\\n/g' <<< "he:llo:you"
he
llo
you
In this particular case, you missed the g
after the substitution. Hence, it is just done once. See:
在这种特殊情况下,您错过g
了替换后的 。因此,它只完成一次。看:
$ echo "string1:string2:string3:string4:string5" | sed s/:/\n/g
string1
string2
string3
string4
string5
g
stands for g
lobal 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.
g
代表g
lobal 并意味着必须在全局范围内进行替换,即对于任何事件。看到默认值是 1,如果你把例子 2,它做了 2 次,等等。
All together, in your case you would need to use:
总之,在您的情况下,您需要使用:
sed 's/:/\n/g' ~/Desktop/myfile.txt
Note that you can directly use the sed ... file
syntax, instead of unnecessary piping: cat file | sed
.
请注意,您可以直接使用sed ... file
语法,而不是不必要的管道:cat file | sed
.
回答by Jiminion
This should do it:
这应该这样做:
cat ~/Desktop/myfile.txt | sed s/:/\n/g
回答by Ed Morton
Using \n
in sed
is non-portable. The portable way to do what you want with sed
is:
使用\n
insed
是不可移植的。做你想做的便携式方式sed
是:
sed 's/:/\
/g' ~/Desktop/myfile.txt
but in reality this isn't a job for sed
anyway, it's the job tr
was created to do:
但实际上,sed
无论如何这都不是一份工作,而是tr
创建该工作的目的:
tr ':' '
' < ~/Desktop/myfile.txt
回答by anubhava
If you're using gnu sed then you can use \x0A
for newline:
如果您使用的是 gnu sed,那么您可以使用\x0A
换行符:
sed 's/:/\x0A/g' ~/Desktop/myfile.txt
回答by potong
This might work for you (GNU sed):
这可能对你有用(GNU sed):
sed 'y/:/\n/' file
or perhaps:
也许:
sed y/:/$"\n"/ file