bash:获取第 n 列输出的最短方法 [英] bash: shortest way to get n-th column of output

查看:31
本文介绍了bash:获取第 n 列输出的最短方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在您的工作日期间,您在 bash 中反复遇到来自某些命令的以下形式的列化输出(在我的情况下是在我的 Rails 工作目录中执行 svn st):

Let's say that during your workday you repeatedly encounter the following form of columnized output from some command in bash (in my case from executing svn st in my Rails working directory):

?       changes.patch
M       app/models/superman.rb
A       app/models/superwoman.rb

为了处理命令的输出 - 在这种情况下是文件名 - 需要某种解析,以便第二列可以用作下一个命令的输入.

in order to work with the output of your command - in this case the filenames - some sort of parsing is required so that the second column can be used as input for the next command.

我一直在做的是使用 awk 来获取第二列,例如当我想删除所有文件时(不是那是典型的用例:),我会这样做:

What I've been doing is to use awk to get at the second column, e.g. when I want to remove all files (not that that's a typical usecase :), I would do:

svn st | awk '{print $2}' | xargs rm

由于我经常打字,一个自然的问题是:在 bash 中是否有更短(因此更酷)的方法来完成此任务?

Since I type this a lot, a natural question is: is there a shorter (thus cooler) way of accomplishing this in bash?

注意:尽管我的具体示例是在我的 svn 工作流程中,但我要问的本质上是一个 shell 命令问题.如果您觉得工作流程很愚蠢并建议采用替代方法,我可能不会投票给您,但其他人可能会投票,因为这里的问题实际上是如何以尽可能最短的方式在 bash 中获取第 n 列命令输出.谢谢:)

NOTE: What I am asking is essentially a shell command question even though my concrete example is on my svn workflow. If you feel that workflow is silly and suggest an alternative approach, I probably won't vote you down, but others might, since the question here is really how to get the n-th column command output in bash, in the shortest manner possible. Thanks :)

推荐答案

您可以使用 cut 访问第二个字段:

You can use cut to access the second field:

cut -f2

抱歉,没有意识到 SVN 在其输出中不使用制表符,所以这有点没用.您可以根据输出定制 cut ,但它有点脆弱 - 像 cut -c 10- 这样的东西可以工作,但确切的值将取决于您的设置.

Sorry, didn't realise that SVN doesn't use tabs in its output, so that's a bit useless. You can tailor cut to the output but it's a bit fragile - something like cut -c 10- would work, but the exact value will depend on your setup.

另一个选项类似于:sed 's/.s+//'

这篇关于bash:获取第 n 列输出的最短方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆