[shell] 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 ....

This question is related to shell sed grep

The answer is


Strictly with sed:

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

don't have to use grep either

an example:

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

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.


How about head ?

echo alonglineoftext | head -c 9

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

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to sed

Retrieve last 100 lines logs How to replace multiple patterns at once with sed? Insert multiple lines into a file after specified pattern using shell script Linux bash script to extract IP address Ansible playbook shell output remove white space from the end of line in linux bash, extract string before a colon invalid command code ., despite escaping periods, using sed RE error: illegal byte sequence on Mac OS X How to use variables in a command in sed?

Examples related to grep

grep's at sign caught as whitespace cat, grep and cut - translated to python How to suppress binary file matching results in grep Linux find and grep command together Filtering JSON array using jQuery grep() Linux Script to check if process is running and act on the result grep without showing path/file:line How do you grep a file and get the next 5 lines How to grep, excluding some patterns? Fast way of finding lines in one file that are not in another?