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

发布于 2024-12-26 04:12:50 字数 506 浏览 0 评论 0原文

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

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

我检查了 awk,我还注意到 bash 有一个 substr 命令,但是我提出的两个解决方案似乎都比它们需要的要长,我可以不要动摇我错过了一些更容易的东西的感觉。

我将发布我找到的两个解决方案作为答案,我欢迎任何批评以及新的解决方案!


已找到解决方案,感谢所有回答的人!

jcollado 和 Mithrandir 之间的关系很接近 - 我将来可能最终会使用两者。 Mithrandir 的答案是一个实际的子字符串,并且更容易查看结果,但 jcollado 的答案让我可以将其通过管道传输到剪贴板,而不会妨碍 EOL 字符。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夜唯美灬不弃 2025-01-02 04:12:50

你想要这样的东西吗:

echo "1234567890" | cut -b 1-6

Do you want something like this:

echo "1234567890" | cut -b 1-6
爱人如己 2025-01-02 04:12:50

使用head -c/--bytes怎么样?

$ echo t9p8uat4ep | head -c 6
t9p8ua

What about using head -c/--bytes?

$ echo t9p8uat4ep | head -c 6
t9p8ua
清引 2025-01-02 04:12:50

我想出了:

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

echo "1234567890" | awk '{print substr($0,1,6)}'

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

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.

在风中等你 2025-01-02 04:12:50

这可能对你有用:

printf "%.6s" 1234567890
123456

This might work for you:

printf "%.6s" 1234567890
123456
浅笑轻吟梦一曲 2025-01-02 04:12:50

如果your_command_herecat

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

If your_command_here is cat:

% OUTPUT=t9p8uat4ep
% cat <<<${OUTPUT:0:6}
t9p8ua
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文