Bash – How to print out all but the last n characters in bash

awkbashsedshelltr

I'm working with standard input (cating two files together) and want all but the last 10 characters of the result to be passed through the next command.

All I can find through searching is using sed, awk or tr to remove the last n characters from each line, or head, tail or rev to remove n lines.

What could I use to do this from standard output piped into a command (hopefully simply and with a single command)?

Example:

Input:
SELECT 'A', 1, GETDATE() UNION ALL
SELECT 'B', 2, GETDATE() UNION ALL
...
SELECT 'Z', 2, GETDATE() UNION ALL

Output:
SELECT 'A', 1, GETDATE() UNION ALL
SELECT 'B', 2, GETDATE() UNION ALL
...
SELECT 'Z', 2, GETDATE()

For what it's worth, I'm using CygWin on Windows, so it needs to be with rather standard and old unix tools 🙁

Best Answer

You could use head:

command | head -c-10

would remove the last 10 bytes from command output.

Quoting from man head:

   -c, --bytes=[-]K
          print the first K bytes of each  file;  with  the  leading  `-',
          print all but the last K bytes of each file

Since you specifically mention that the 10 characters to be removed would occur on one line, you could use sed too. Pipe the command output to:

sed '$s/\(.\{10\}\)$//'

or if your sed supports extended regex:

sed -r '$s/.{10}$//'

The syntax would be similar using perl:

perl -pe 's/.{10}$// if eof'
Related Question