sed delete remaining characters in line except first 5

☆樱花仙子☆ 提交于 2019-12-08 17:36:18

问题


what would be sed command to delete all characters in line except first 5 leading ones, using sed? I've tried going 'backwards' on this (reverted deleting) but it's not most elegant solution.


回答1:


This might work for you (GNU sed):

echo '1234567890' | sed 's/.//6g'
12345

Or:

echo '1234567890' | cut -c-5
12345



回答2:


Try this (takes 5 repetitions of 'any' character at the beginning of the line and save this in the first group, then take any number of repetition of any characters, and replace the matched string with the first group):

sed 's/^\(.\{5\}\).*/\1/'

Or the alternative suggested by mouviciel:

sed 's/^\(.....\).*/\1/'

(it is more readable as long as the number of first characters you want does not grow too large)



来源:https://stackoverflow.com/questions/10718326/sed-delete-remaining-characters-in-line-except-first-5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!