正则表达式-用句点替换行首中的所有空格 [英] Regular expression - replace all spaces in beginning of line with periods
问题描述
我不在乎是否通过vim,sed,awk,python等来实现.我尝试了全部,却无法完成.
I don't care if I achieve this through vim, sed, awk, python etc. I tried in all, could not get it done.
对于这样的输入:
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
我想要:
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f1 f2 f3
......sub21 f1 f2 f3
...sub3 f1 f2 f3
然后我想将其加载到Excel中(由空格分隔),并且仍然能够查看第一列的层次结构!
Then I want to just load this up in Excel (delimited by whitespace) and still be able to look at the hierarchy-ness of the first column!
我尝试了很多事情,但最终失去了层次结构信息
I tried many things, but end up losing the hierarchy information
推荐答案
以此作为输入:
$ cat file
top f1 f2 f3
sub1 f1 f2 f3
sub2 f1 f2 f3
sub21 f1 f2 f3
sub3 f1 f2 f3
尝试:
$ sed -E ':a; s/^( *) ([^ ])/\1.\2/; ta' file
top f1 f2 f3
...sub1 f1 f2 f3
...sub2 f1 f2 f3
......sub21 f1 f2 f3
...sub3 f1 f2 f3
工作方式:
-
:a
这将创建标签
a
.s/^( *) ([^ ])/\1.\2/
如果行以空格开头,则将前导空格中的最后一个空格替换为句点.
If the line begins with spaces, this replaces the last space in the leading spaces with a period.
更详细地讲,
^( *)
匹配除最后一个以外的所有前导空格,并将它们存储在组1中.regex([^ ])
(尽管有stackoverflow的样子,但它由空格和([^ ])
组成)匹配一个空白,后跟一个非空白,并将该非空白存储在组2中.In more detail,
^( *)
matches all leading blanks except the last and stores them in group 1. The regex([^ ])
(which, despite what stackoverflow makes it look like, consists of a blank followed by([^ ])
) matches a blank followed by a nonblank and stores the nonblank in group 2.\1.\2
将匹配的文本替换为第1组,然后是句点,然后是第2组.\1.\2
replaces the matched text with group 1, followed by a period, followed by group 2.ta
如果替换命令导致替换,则分支回到标签
a
并重试.If the substituted command resulted in a substitution, then branch back to label
a
and try over again.-
以上已在现代GNU sed上进行了测试.对于BSD/OSX sed,可能需要或可能不需要使用:
The above was tested on modern GNU sed. For BSD/OSX sed, one might or might not need to use:
sed -E -e :a -e 's/^( *) ([^ ])/\1.\2/' -e ta file
在古老的GNU sed上,需要使用
-r
代替-E
:On ancient GNU sed, one needs to use
-r
in place of-E
:sed -r ':a; s/^( *) ([^ ])/\1.\2/; ta' file
-
-
以上假设空格为空白.如果它们是制表符,那么您将必须确定您的制表符是什么,并相应地进行替换.
The above assumed that the spaces were blanks. If they are tabs, then you will have to decide what your tabstop is and make substitutions accordingly.
这篇关于正则表达式-用句点替换行首中的所有空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!