Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

capture first n characters of every line

Tags:

regex

grep

I'm having troubles capturing the first 6 characters of every line. Supposing I have the following lines inside text.txt:

this is a sentence
1234567890
string

I would like to get the first 10 chars:

this i
123456
string

I've tried running grep -Eo "^[a-zA-Z0-9]*{6}" text.txt

But grep recycles the regex at every 6th position instead of starting at the next new line. it ends up returning:

this i
s a se
ntence
123456
7890..

what am I doing wrong here?

like image 776
Paolo Avatar asked Oct 23 '25 18:10

Paolo


2 Answers

Why to use grep, you can use simple cut command:

cut -c1-6 file

OR else this more complex sed will also work:

sed 's/^\(.\{6\}\).*$/\1/' file
like image 110
anubhava Avatar answered Oct 26 '25 08:10

anubhava


Use following command:

grep -Eo "^.{6}" text.txt

Above command omit lines with <6 characters. To include such lines, use following command:

grep -Eo "^.{1,6}" text.txt
like image 24
falsetru Avatar answered Oct 26 '25 10:10

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!