ChatGPT解决这个技术问题 Extra ChatGPT

Using sed, how do you print the first 'N' characters of a line?

Using sed what is an one liner to print the first n characters? I am doing the following:

grep -G 'defn -test.*' OctaneFullTest.clj  | sed ....

P
Paulo Mattos

Don't use sed, use cut:

grep .... | cut -c 1-N

If you MUST use sed:

grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

Actually on a Cygwin system I'm working on now cut doesn't cut it while sed does.
Or even sed -r 's/^(.{12}).*/\1/'.
@fedorqui -r is apparently available on Linux, but not on Mac.
Exactly, it is not available on OSX.
FYI: cut -c 1-N (where N is a number) does work on my Cygwin installation (cygwin v. 2.6, cut v. 8.25) On OS X, use sed -E rather than sed -r, used elsewhere.
r
rjmunro
colrm x

For example, if you need the first 100 characters:

cat file |colrm 101 

It's been around for years and is in most linux's and bsd's (freebsd for sure), usually by default. I can't remember ever having to type apt-get install colrm.


This doesn't give the first 50n characters. It gives the n characters for every line of text
And colrm understands utf8.
g
ghostdog74

don't have to use grep either

an example:

sed -n '/searchwords/{s/^\(.\{12\}\).*/\1/g;p}' file

D
Diego Sevilla

Strictly with sed:

grep ... | sed -e 's/^\(.\{N\}\).*$/\1/'

S
SLePort

To print the N first characters you can remove the N+1 characters up to the end of line:

$ sed 's/.//5g' <<< "defn-test"
defn

S
Sergey Papyan

How about head ?

echo alonglineoftext | head -c 9

I wonder how/if this works with non-ASCII/multi-byte characters