使用 sed/awk 交换第三列中的字符
A 文件有 3 列:
123711184642,3583090366663629,0036f920012437d4 123715942138,3538710295145500,0136f920afd6c643
我想删除第三列中的前两个字符: 123711184642,3583090366663629,36f920012437d4 123715942138,3538710295145500,36f920afd6c643
并交换第三列的前 6 个字符,两两交换,最终结果为: 123711184642,3583090366663629,639f02012437d4 123715942138,3538710295145500,639f02afd6c643
任何帮助将不胜感激。 伯尼
A files has 3 columns:
123711184642,3583090366663629,0036f920012437d4
123715942138,3538710295145500,0136f920afd6c643
I want to delete the first two characters in the third column:
123711184642,3583090366663629,36f920012437d4
123715942138,3538710295145500,36f920afd6c643
And swap the first 6 characters, in twos, of the third column such that the final result is:
123711184642,3583090366663629,639f02012437d4
123715942138,3538710295145500,639f02afd6c643
Any assistance will be appreciated.
Bernie
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
假设您的输入数据位于文件“foo”中,您可以这样做:
其中 awkfile 将包含:
Assuming your input data is in the file "foo", you could do:
where awkfile would contain:
对于 sed,这只是分组的问题:
With sed it's just a matter of grouping:
与呆呆:
With gawk:
sed
1 行。不在乎你有多少个字段,只要你只想改变最后一个字段即可。它也不关心最后一个字段有多少对,它会以相同的方式交换它们。sed 'h;s/^.,..//;s/(.)(.)/\2\1/g;x;s/,[^,]$ /,/;G;s/\n//' /path/to/file输入
输出
说明
h
-- 复制整个s/^.* ,..//
-- 现在模式空间仅保留最后一个字段及其
删除了两个前导数字
s/\(.\)\(.\)/\2\1/g
-- 计算数字在模式空间上成对交换
x
——用hold交换模式空间space
s/,[^,]*$/,/
-- 删除整个最后一个字段
G
-- 将保留空间附加到模式空间之间有 '\n'
他们
s/\n//
-- 删除添加的 '\n'G
sed
1-liner. Doesn't care how many fields you have as long as you just want to alter the last. It also doesn't care how many pairs the last field has, it will swap them just the same.sed 'h;s/^.,..//;s/(.)(.)/\2\1/g;x;s/,[^,]$/,/;G;s/\n//' /path/to/fileInput
Output
Explanation
h
-- make a copy of the entires/^.*,..//
-- Pattern space nowholds only the last field with its
two leading numbers removed
s/\(.\)\(.\)/\2\1/g
-- Do the numberswap in pairs on the pattern space
x
-- swap pattern space with holdspace
s/,[^,]*$/,/
-- Remove the entirelast field
G
-- Append the hold space to thepattern space with an '\n' between
them
s/\n//
-- Remove the '\n' added byG
awk
一行代码只是为了好玩。这并不关心第三个字段中有多少对数字,它适用于所有数字。awk -F, '{$3=substr(gensub(/(.)(.)/,"\2\1","g",$3),3)}1' OFS=, /path/to /file输入
输出
awk
1-liner just for the fun of it. This doesn't care how many pairs of numbers are in the 3rd field, it will work on all of them.awk -F, '{$3=substr(gensub(/(.)(.)/,"\2\1","g",$3),3)}1' OFS=, /path/to/fileInput
Output