带有管道和标准输入的 Bash 子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8809411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:16:25  来源:igfitidea点击:

Bash substring with pipes and stdin

bash

提问by Nick Knowlson

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.

我的目标是将命令的输出减少到任意数量的字符(让我们使用6)。我希望能够将此命令附加到管道的末尾,因此它应该能够仅使用 stdin。

echo "1234567890" | your command here 
# desired output: 123456

I checked out awk, and I also noticed bash has a substrcommand, 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. 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.

jcollado 和 Mithrandir 之间的距离很近——我将来可能最终会同时使用两者。Mithrandir 的答案是一个实际的子字符串,并且更容易查看结果,但是 jcollado 的答案让我可以将它通过管道传输到剪贴板,而不会出现 EOL 字符。

回答by Mithrandir

Do you want something like this:

你想要这样的东西:

echo "1234567890" | cut -b 1-6

回答by jcollado

What about using head -c/--bytes?

怎么用head -c/--bytes

$ echo t9p8uat4ep | head -c 6
t9p8ua

回答by Nick Knowlson

I had come up with:

我想出了:

echo "1234567890" | ( read h; echo ${h:0:6} )

and

echo "1234567890" | awk '{print substr(
printf "%.6s" 1234567890
123456
,1,6)}'

But both seemed like I was using a sledgehammer to hit a nail.

但两者都像是我在用大锤敲钉子。

回答by potong

This might work for you:

这可能对你有用:

% OUTPUT=t9p8uat4ep
% cat <<<${OUTPUT:0:6}
t9p8ua

回答by eduffy

If your_command_hereis cat:

如果your_command_herecat

##代码##