插入“,"在文本的特定位置 [英] Inserting a "," in a particular position of a text

查看:79
本文介绍了插入“,"在文本的特定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我输入了准确的文本和执行的命令,因此看起来有些混乱.)

(I put a exact text and command I executed so would be looking a bit messy.)

我有一个看起来像.TXT的文件

I have a .TXT file looking like

11111111111111111111111111111111111111111111111111111111111111111111111
11111111111111111111111111111111111111111111111111111111111111111111111

我想要的结果会是

11111111111111,1111111,11,1,111,1111111111111,1,11111111,1111111111111111,111,111
11111111111111,1111111,11,1,111,1111111111111,1,11111111,1111111111111111,111,111

我尝试过的命令是

sed -i 's/\(.\{14\}\)\(.\{7\}\)\(.\{2\}\)\(.\{1\}\)\(.\{3\}\)\(.\{13\}\)\(.\{1\}\)\(.\{8\}\)\(.\{16\}\)\(.\{3\}\)/\1,\2,\3,\4,\5,\6,\7,\8,\9,\10,/' SOME.TXT

我得到的结果是

11111111111111,1111111,11,1,111,1111111111111,1,11111111,1111111111111111,1111111111111110,111
11111111111111,1111111,11,1,111,1111111111111,1,11111111,1111111111111111,1111111111111110,111

我真的不知道为什么这些0突然弹出,并且即使在中途工作,"也不会出现在我命令的位置.

I have literally no idea why these 0s suddenly popped out and ' , ' doesn't appear in the position where I command even though it worked half way.

这是bug还是sed命令中的某些东西?

Is this a bug or something in sed command?

推荐答案

它在输出中打印0,因为sed捕获组及其后向引用最多只能有9个,并且\10被解释为\1,然后是文字0.

It is printing 0 in output because sed capture groups and their back-references can be up to 9 only and \10 is interpreted as \1 followed by literal 0.

您可以使用gnu-awk FIELDWIDTHS功能轻松解决此问题:

You can solve it easily using FIELDWIDTHS feature of gnu-awk:

awk -v OFS=, 'BEGIN { FIELDWIDTHS = "14 7 2 1 3 13 1 8 16 3 *" } {$1 = $1} 1' file

11111111111111,1111111,11,1,111,1111111111111,1,11111111,1111111111111111,111,111
11111111111111,1111111,11,1,111,1111111111111,1,11111111,1111111111111111,111,111


仅用于学术练习,下面是一个有效的sed,它使用2个替代方法来解决此问题:


Just for academic exercise, here is a working sed to solve this using 2 substitutions:

sed -E 's/(.{14})(.{7})(.{2})(.)(.{3})(.{13})(.)(.{8})(.+)/\1,\2,\3,\4,\5,\6,\7,\8,\9/; s/(.+,.{16})(.{3})(.*)/\1,\2,\3/' file

这篇关于插入“,"在文本的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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