sed,用该行的第一部分全局替换一个分隔符 [英] sed, replace globally a delimiter with the first part of the line
问题描述
假设我有以下几行:
<前>1:a:b:c2:d:e:f3:a:b4:a:b:c:d:e:f我如何使用 sed(或 perl)编辑它以便阅读:
<前>1a1b1c2d2e2f3a3b4a4b4c4d4e4f我用过这样的 awk:
<前>awk -F':' '{gsub(/:/, $1, $0);打印 $0}'但需要很长时间才能完成!所以寻找更快的东西.
'这有点棘手,但可以用 sed
完成(假设文件 data
包含样本输入):
$ sed '/^\(.\):/{s//\1/: 重试s/^\(.\)\([^:]*\):/\1\2\1/重试}' 数据1a1b1c2d2e2f3a3b4a4b4c4d4e4f$
您可以将脚本用分号拼成一行;MacOS X 上的 sed
有时有点胡思乱想,并且反对某些部分,所以它分为 6 行.第一行匹配以单个字符和冒号开头的行,并在识别时启动一系列操作.例如,第一个替换将1:"替换为1".: retry
也是分支的标签——这是其中的关键部分.下一个替换复制第一个冒号上的行中的第一个字符.t retry
如果替代品改变了任何东西,则返回标签.最后一行分隔了最初匹配行的整个操作序列.
Lets say I have the following lines:
1:a:b:c 2:d:e:f 3:a:b 4:a:b:c:d:e:f
how can I edit this with sed (or perl) in order to read:
1a1b1c 2d2e2f 3a3b 4a4b4c4d4e4f
I have done with awk like this:
awk -F':' '{gsub(/:/, $1, $0); print $0}'
but takes ages to complete! So looking for something faster.
'Tis a tad tricky, but it can be done with sed
(assuming the file data
contains the sample input):
$ sed '/^\(.\):/{
s//\1/
: retry
s/^\(.\)\([^:]*\):/\1\2\1/
t retry
}' data
1a1b1c
2d2e2f
3a3b
4a4b4c4d4e4f
$
You may be able to flatten the script to one line with semi-colons; sed
on MacOS X is a bit cranky at times and objected to some parts, so it is split out into 6 lines. The first line matches lines starting with a single character and a colon and starts a sequence of operations for when that is recognized. The first substitute replaces, for example, '1:' by just '1'. The : retry
is a label for branching too - a key part of this. The next substitution copies the first character on the line over the first colon. The t retry
goes back to the label if the substitute changed anything. The last line delimits the entire sequence of operations for the initially matched line.
这篇关于sed,用该行的第一部分全局替换一个分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!