[英]Bash substring with pipes and stdin
My goal is to cut the output of a command down to an arbitrary number of characters (let's use 6 ). 我的目标是将命令的输出缩减为任意数量的字符(让我们使用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. 我希望能够将此命令附加到管道的末尾,因此它应该只能使用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. 我检查了awk
,我还注意到bash有一个substr
命令,但是我想出的两个解决方案似乎都比他们需要的更长,而且我也无法摆脱自己缺少一些东西的感觉。
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. jcollado和Mithrandir之间的距离很近-将来我可能会同时使用它们。 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. Mithrandir的答案是一个实际的子字符串,并且更易于查看结果,但是jcollado的答案使我可以将它以不带EOL字符的方式传递到剪贴板。
您想要这样的东西吗?
echo "1234567890" | cut -b 1-6
What about using head -c/--bytes
? 使用head -c/--bytes
呢?
$ echo t9p8uat4ep | head -c 6
t9p8ua
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. 但是两者都好像我在用大锤砸钉子。
This might work for you: 这可能对您有用:
printf "%.6s" 1234567890
123456
If your_command_here
is cat
: 如果your_command_here
是cat
:
% OUTPUT=t9p8uat4ep
% cat <<<${OUTPUT:0:6}
t9p8ua
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.