Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash substring with pipes and stdin

Tags:

bash

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.

like image 430
Nick Knowlson Avatar asked Jan 10 '12 19:01

Nick Knowlson


4 Answers

Do you want something like this:

echo "1234567890" | cut -b 1-6
like image 137
Mithrandir Avatar answered Oct 19 '22 04:10

Mithrandir


What about using head -c/--bytes?

$ echo t9p8uat4ep | head -c 6
t9p8ua
like image 29
jcollado Avatar answered Oct 19 '22 03:10

jcollado


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.

like image 34
Nick Knowlson Avatar answered Oct 19 '22 04:10

Nick Knowlson


This might work for you:

printf "%.6s" 1234567890
123456
like image 2
potong Avatar answered Oct 19 '22 02:10

potong