简体   繁体   English

sed替换与python替换

[英]sed replace versus python replace

The format of the output is the same except that when using python, the output adds a new line between each string. 输出的格式是相同的,除了使用python时,输出在每个字符串之间添加一个新行。 Any idea why and how I can do this using sed? 知道为什么以及如何使用sed做到这一点?

sed 's:\x01: | :g'

01.06.2012 07:51:55.135 | 3732 | INFO | xxx | 8=FIX.4.2 | 9=157 | 35=V | 56=xxx | 49=xxx | 52=20120601-07:51:54 | 34=40 | 262=VMD1338537114945 | 263=1 | 264=0 | 265=1 | 
01.06.2012 07:51:55.135 | 3732 | INFO | xxx | 8=FIX.4.2 | 9=157 | 35=V | 56=xxx | 49=xxx | 52=20120601-07:51:54 | 34=41 | 262=VLT1338537114945 | 263=1 | 264=1 | 265=1 | 

for line in sys.stdin:
    print line.replace("\01", " | ")


01.06.2012 07:51:55.135 | 3732 | INFO | xxx | 8=FIX.4.2 | 9=157 | 35=V | 56=xxx | 49=xxx | 52=20120601-07:51:54 | 34=40 | 262=VMD1338537114945 | 263=1 | 264=0 | 265=1 | 

01.06.2012 07:51:55.135 | 3732 | INFO | xxx | 8=FIX.4.2 | 9=157 | 35=V | 56=xxx | 49=xxx | 52=20120601-07:51:54 | 34=41 | 262=VLT1338537114945 | 263=1 | 264=1 | 265=1 | 

I'm not a sed guru, but you can add a newline at the end of every line in sed using the following: 我不是sed guru,但您可以使用以下内容在sed中的每一行末尾添加换行符:

 sed -e 's/$/\n/g'

This works because $ matches the end of a line. 这是因为$匹配一行的结尾。 Note that you can string multiple sed commands together with -e (as pointed out by Michael Mrozek -- see man sed for more info). 请注意,您可以将多个sed命令与-e串联起来(如Michael Mrozek所指出 - 请参阅man sed以获取更多信息)。

Add a second substitution that replaces the end of the line with a newline: s/$/\\n/ . 添加第二个替换,用换行符替换行的结尾: s/$/\\n/ Since you have two patterns now, you need to use -e : 既然你现在有两个模式,你需要使用-e

sed -e 's:\x01: | :g' -e 's/$/\n/'

This might work for you: 这可能对你有用:

sed '/\x01/{s// | /g;G}' file

Or if you just want to add a newline to every line: 或者,如果您只想为每一行添加换行符:

sed G file

print添加一个新行试试这个

sys.stdout.write(line.replace("\01"," | "))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM