Reputation: 7426
My goal is to cut the output of a command down to an arbitrary number of characters (let's use 6). I would like to be able to append this command to the end of a pipeline, so it should be able to just use stdin.
echo "1234567890" | your command here
# desired output: 123456
I checked out awk
, and I also noticed bash has a substr
command, but both of the solutions I've come up with seem longer than they need to be and I can't shake the feeling I'm missing something easier.
I'll post the two solutions I've found as answers, I welcome any critique as well as new solutions!
Solution found, thank you to all who answered!
It was close between jcollado and Mithrandir - I will probably end up using both in the future. Mithrandir's answer was an actual substring and is easier to view the result, but jcollado's answer lets me pipe it to the clipboard with no EOL character in the way.
Upvotes: 20
Views: 20678
Reputation: 7426
I had come up with:
echo "1234567890" | ( read h; echo ${h:0:6} )
and
echo "1234567890" | awk '{print substr($0,1,6)}'
But both seemed like I was using a sledgehammer to hit a nail.
Upvotes: 6
Reputation: 40232
If your_command_here
is cat
:
% OUTPUT=t9p8uat4ep
% cat <<<${OUTPUT:0:6}
t9p8ua
Upvotes: 0
Reputation: 40414
What about using head -c/--bytes
?
$ echo t9p8uat4ep | head -c 6
t9p8ua
Upvotes: 7
Reputation: 25387
Do you want something like this:
echo "1234567890" | cut -b 1-6
Upvotes: 41