Bash:sed -n参数 [英] Bash : sed -n arguments

查看:189
本文介绍了Bash:sed -n参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在读取ls实例的结果时,我试图使用sed从特定行显示特定术语:

While reading results of a ls instance, I'm trying to display a specific term from a specific line using sed :

这是我设法做到的,直到现在:

Here is what I managed to do until now :

echo $(ls -lAtro | sed -n '3p' | cut -d' ' -f 6 )

这是在读第三行的第六项。我正在尝试用一个更简单的变量替换 3p,该变量将允许执行以下操作:

This is reading the 6th term of the 3rd line. What I'm trying to do is replace the '3p' by a more simple variable which would permit to do something like this :

linetoread=3
echo $(ls -lAtro | sed -n "$linetoread" | cut -d' ' -f 6 )

上面的示例当然行不通,但是您知道了。我该怎么做呢?

The above example doesn't work of course, but you get the idea. What can I do to achieve this ? Thanks in advance.

推荐答案

请尝试 awk 代替-

line=3 ; 
ls -lAtro | awk -v var="$line" 'NR==var {print $6}' 

变量 line = 3 并将其输入到 awk awk -v 部分)。

This takes the variable line=3 and feeds it into awk (the awk -v part).

NR == var 确保获得与变量对应的行

The NR==var ensures that you get the line corresponding to your variable.

然后,您可以更改 print $ 6 部分以匹配所需的任何列。请注意,默认的分隔符是空格。

Then you can change the print $6 part to match whichever column you want. Note that the default delimiter is a space.

当然,正如注释中所指出的那样,您不应该解析 ls的输出

Of course, as pointed out in the comments, you shouldn't be parsing the output of ls.

这篇关于Bash:sed -n参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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