5

How can you limit the count of standard output characters that is redirected to file?

3 Answers 3

8

Other ways (external)

echo $out| head -c 20
echo $out | awk '{print substr($0,1,20) }'
echo $out | ruby -e 'print $_[0,19]'
echo $out | sed -r 's/(^.{20})(.*)/\1/'
Sign up to request clarification or add additional context in comments.

Comments

1

You could use Command Substitution to wrap the output pre-redirection, then use the offset Parameter Expansion to limit the number of characters like so:

#!/bin/bash

limit=20

out=$(echo "this line has more than twenty characters in it")
echo ${out::limit} > /path/to/file

Proof of Concept

$ limit=20
$ out=$(echo "this line has more than twenty characters in it").
$ echo ${out::limit}
this line has more t

2 Comments

Cripes, I never cease to be amazed at how much I don't know about bash.
@sarnold Parameter Expansion seems to be the biggest undervalued/unknown feature of not just bash but any POSIX compliant shell. Time after time I see people calling basename or dirname which both can be done in native shell syntax using Parameter Expansion. See HERE for a good link on usage as well as a great site on bash.
0

You can't do so directly into a file, but you can pipe through sed or head, etc. to pass on only part of the output. Or as @SiegeX says, capture the output in the shell (but I would be wary of that if the output mis likely to be large).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.