user1246172
user1246172

Reputation: 1115

sed delete remaining characters in line except first 5

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.

Upvotes: 7

Views: 4792

Answers (2)

potong
potong

Reputation: 58483

This might work for you (GNU sed):

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

Or:

echo '1234567890' | cut -c-5
12345

Upvotes: 11

Antoine
Antoine

Reputation: 5198

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)

Upvotes: 3

Related Questions