大佬教程收集整理的这篇文章主要介绍了使用 sed 删除特定数量的数字,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
John,1234567
Bob,2839211
Alex,2817821
Mary,9371281
我目前正在尝试使用 sed 检索带有第二列最后 4 位数字的第一列,因此输出应如下所示:
John,4567
Bob,9211
Alex,7821
Mary,1281
这是我的命令:'s/\(.*,\)\(.*\)//'
,我认为这个命令匹配第一列直到逗号和第二列直到结束,但我不确定如何继续。
只需捕获每行的最后四位数字并删除任何前面的数字:
$ sed 's/[0-9]*\([0-9]\{4\}\)$/\1/' input.txt
John,4567
Bob,9211
Alex,7821
Mary,1281
如果使用支持 POSIX 扩展正则表达式的 sed
版本,可以稍微清理一下
sed -E 's/[0-9]*([0-9]{4})$/\1/' input.txt
,
如果您对 awk
没问题,请尝试以下操作。使用 GNU awk
中的示例编写和测试。
awk 'BEGIN{FS=OFS=","} {$2=substr($2,length($2)-3)} 1' Input_file
说明:为以上添加详细说明。
awk ' ##StarTing awk program from here.
BEGIN{ ##StarTing BEGIN section of this program from here.
FS=OFS="," ##SetTing FS and OFS to comma space here.
}
{
$2=substr($2,length($2)-3) ##GetTing last 4 digits now in 2nd field here.
}
1 ##prinTing current edited/non-edited line.
' Input_file ##Mentioning Input_file name here.
@H_197_53@
@H_197_53@
第二个解决方案:再添加 1 个解决方案,以防您的第二列可能包含数字和其他@R_950_11058@混合,那么以下可能对您有所帮助。
awk 'BEGIN{FS=OFS=","} {gsub(/[^0-9]+/,"",$2);$2=substr($2,length($2)-3)} 1' Input_file
说明:为以上添加详细说明。
awk ' ##StarTing awk program from here.
BEGIN{ ##StarTing BEGIN section of this program from here.
FS=OFS="," ##SetTing FS and OFS to comma space here.
}
{
gsub(/[^0-9]+/,$2) ##Globally substituTing everything apart from digits with NULL in 2nd field.
$2=substr($2,length($2)-3) ##getTing last 4 digits now in 2nd field here.
}
1 ##prinTing current edited/non-edited line.
' Input_file ##Mentioning Input_file name here.
,
你可以使用
sed 's/^\([^,]*\),*[0-9]*\([0-9]\{4\}\).*/\1,\2/' file
参见online demo。
详情
^
- 字符串的开始\([^,]*\)
- 第 1 组:除逗号之外的任何零个或多个字符,*
- 一个逗号和零个或多个空格[0-9]*
- 零个或多个数字\([0-9]\{4\}\)
- 第 2 组:四位数.*
- 该行的其余部分\1,\2
- 替换为:第 1 组、,
、空格和第 2 组值。类似于 KamilCuk 的答案,除了使用 POSIX 字符类并锚定要删除的数字:
sed 's/,[[:digit:]]\{3\}/,/'
,
如果文件格式只是 <text only alphanumeric characters>,<number exactly 7 digits>
,您可以删除前 3 位数字:
sed 's/[0-9][0-9][0-9]//'
以上是大佬教程为你收集整理的使用 sed 删除特定数量的数字全部内容,希望文章能够帮你解决使用 sed 删除特定数量的数字所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。