bash 如何在另一个命令中使用 awk 的输出?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3452339/
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-17 22:28:10  来源:igfitidea点击:

How do I use output from awk in another command?

bashawkpipeline

提问by

So I need to convert a date to a different format. With a bash pipeline, I'm taking the date from the last console login, and pulling the relevant bits out with awk, like so:

所以我需要将日期转换为不同的格式。使用 bash 管道,我从上次控制台登录中获取日期,并使用 awk 提取相关位,如下所示:

last $USER | grep console | head -1 | awk '{print , }'

Which outputs: Aug 08($4=Aug $5=08, in this case.)

输出:(Aug 08在这种情况下,$4=Aug $5=08。)

Now, I want to take 'Aug 08' and put it into a datecommand to change the format to a numerical date.

现在,我想将 'Aug 08' 放入一个date命令中,以将格式更改为数字日期。

Which would look something like this:

看起来像这样:

date -j -f %b\ %d Aug\ 08 +%m-%d

Outputs: 08-08

输出:08-08

The question I have is, how do I add that to my pipeline and use the awk variables $4 and $5 where 'Aug 08' is in that date command?

我的问题是,如何将它添加到我的管道并使用 awk 变量 $4 和 $5 ,其中“Aug 08”在该日期命令中?

采纳答案by Cascabel

You just need to use command substitution:

您只需要使用命令替换:

date ... $(last $USER | ... | awk '...') ...

Bash will evaluate the command/pipeline inside the $(...)and place the result there.

Bash 将评估里面的命令/管道$(...)并将结果放在那里。

回答by Gilles 'SO- stop being evil'

Get awkto call date:

获取awk到的呼叫date

... | awk '{system("date -j -f %b\ %d \""   "\" +%b-%d")}'

Or use process substitution to retrieve the output from awk:

或者使用进程替换从awk以下位置检索输出:

date -j -f %b\ %d "$(... | awk '{print , }')" +%b-%d

回答by Starkey

Using back ticks should work to get the output of your long pipeline into date.

使用反勾号应该可以使您的长管道的输出保持最新。

date -j -f %b\ %d \`last $USER | grep console | head -1 | awk '{print , }'\` +%b-%d

回答by dockeryZ

I'm guessing you already tried this?

我猜你已经试过了?

last $USER | grep console | head -1 | awk | date -j -f %b\ %d   +%b-%d