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

ShellSedGrep

Shell Problem Overview


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 ....

Shell Solutions


Solution 1 - Shell

Don't use sed, use cut:

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

If you MUST use sed:

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

Solution 2 - Shell

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.

Solution 3 - Shell

don't have to use grep either

an example:

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

Solution 4 - Shell

Strictly with sed:

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

Solution 5 - Shell

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

Solution 6 - Shell

How about head ?

echo alonglineoftext | head -c 9

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBerlin BrownView Question on Stackoverflow
Solution 1 - ShellPaul TomblinView Answer on Stackoverflow
Solution 2 - ShellmanoflinuxView Answer on Stackoverflow
Solution 3 - Shellghostdog74View Answer on Stackoverflow
Solution 4 - ShellDiego SevillaView Answer on Stackoverflow
Solution 5 - ShellSLePortView Answer on Stackoverflow
Solution 6 - ShellSergey PapyanView Answer on Stackoverflow