0

This question is an exact duplicate of:

I have a file with many lines, and I want to trim each line to be 80 characters in length. How could I do this?

I have already filtered out lines shorter than 80 characters, so now I'm left with a file that has lines 80+ characters in length and I want to trim each line so that all are exactly 80. In other words I want to preserve the first 80 characters in each line and remove the rest of the line.

marked as duplicate by αғsнιη, Rui F Ribeiro linux May 30 '18 at 19:18

This question was marked as an exact duplicate of an existing question.

4

You can use the cut command:

cut -c -80 file

With grep:

grep -Eo '.{80}' file
  • I only want to cut each line in the file to 80, the file itself has thousands of lines, each line longer than 80 characters. – mah May 30 '18 at 17:31
  • @mah That is what this command does. – Jesse_b May 30 '18 at 17:31
  • Well, not exactly, cut counts bytes (not characters). – Isaac May 30 '18 at 17:59
  • @Isaac: True for GNU cut – Jesse_b May 30 '18 at 18:04
  • 1
    Alright yeah it's not working with gnu cut afterall, bsd cut works fine though. macos – Jesse_b May 30 '18 at 18:33
2

To cut (truncate) each line of the file (and have the output in the present console) use:

cut -c -80 infile               # cut only counts bytes (fail with utf8)
grep -o '^.\{1,80\}' infile
sed 's/\(^.\{1,80\}\).*/\1/' infile

If what you want is to insert a newline at the 80 character and split each line longer than 80 characters into more lines, use:

fold -w 80 infile            # fold, like cut, counts bytes.

If you want to split only at spaces (whole words), use:

fold -sw 80 infile

For all the solutions above, redirect to some other file like >outfile (do not use the same name, that will not work) at the end of any command to store the result in outfile. Example:

fold -sw 80 infile > outfile
2

Using AWK:

awk '{print substr($0,1,80)}' file.txt

Using cut:

 cut -c -80 file.txt

Using colrm:

colrm 81 file.txt

Using sed:

sed 's/^\(.\{80\}\).*$/\1/' file.txt

Using grep:

grep -Eo '.{80}' file.txt
  • awk worked for me. grep did not. I didn't try the others. Thanks for the solution I needed! – IdusOrtus Apr 5 at 16:28
0

With sed:

sed 's/^\(.\{80\}\).*$/\1/' file

With cut:

cut -c -80 file 

Not the answer you're looking for? Browse other questions tagged or ask your own question.