Bash substring with pipes and stdin
Solution 1
Do you want something like this:
echo "1234567890" | cut -b 1-6
Solution 2
What about using head -c/--bytes
?
$ echo t9p8uat4ep | head -c 6
t9p8ua
Solution 3
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.
Solution 4
This might work for you:
printf "%.6s" 1234567890
123456
Related videos on Youtube
Nick Knowlson
Hi, I'm Nick Knowlson and two things I can't get enough of are programming and reading. I live in Victoria, BC with my fiance Samantha and our cats Ruby and Ada. I'm a software developer and I love building things. I take pride in the quality of my work and enjoy actively improving my skills. I can write code in many languages, but I am most comfortable in C# and Ruby at the moment. Check out my website for more information.
Updated on June 04, 2022Comments
-
Nick Knowlson almost 2 years
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 asubstr
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.
-
Nick Knowlson over 12 yearsThanks, that's quite nice as well! Actually, even a bit better since it doesn't include an EOL character.
-
Nick Knowlson over 12 yearsThe only problem with this is I did want something I could append on to the end of a pipeline, something that was able to just use stdin. I will edit the question to make that clearer.
-
Sirex over 10 yearsis that meant to be | ( read h; echo ${h:0:6} ) in the first example ?
-
Nick Knowlson over 10 yearsHonestly, I can't really remember. I just tried it again now and it works both ways for me in zsh, but in bash only seems to work with parentheses. So I guess maybe it is, thanks! :)