【问题标题】:bash print table in one line not in multiple linesbash 一行打印表格而不是多行
【发布时间】:2023-01-27 00:00:22
【问题描述】:

当我直接运行命令时,我有一个来自路由器的表格格式,它在一行中打印,但是当我将相同的命令放在 for 循环中时,我得到不同行的输出。为什么会发生这种情况,我怎样才能阻止它发生?

我有兴趣获取接口名称和每个接口的 ip,并将它们存储到一个变量中以放入命令中,但我什至无法存储以太网名称。

for s in `show ip interfaces | grep Ethernet0`; do 
  ethernet=`echo $s | cut -d ' ' -f 1`
  #ip=`echo $s | cut -d ' ' -f 2`
  echo "this is the ethernet $ethernet";
done

admin@sonic:~$ for s in `show ip interfaces | grep Ethernet0`; do 
>   ethernet=`echo $s | cut -d ' ' -f 1`
>   echo "remove $ethernet";
> done
remove Ethernet0
remove 10.0.0.0/31
remove up/down
remove ARISTA01T2
remove 10.0.0.1
admin@sonic:~$ show ip interfaces | grep Ethernet0
Ethernet0              10.0.0.0/31          up/down       ARISTA01T2      10.0.0.1
admin@sonic:~$ 

【问题讨论】:

  • 因为你DRLWF
  • 跳过/过滤掉包含句点或正斜杠的 s 值?

标签: bash


【解决方案1】:
ethernet=`echo $s | cut -d ' ' -f 1`

$s 中没有空格,因此整个值被视为第一个字段。

当我想用空格分隔字段时,我通常使用awk

% echo 'Ethernet0              10.0.0.0/31          up/down       ARISTA01T2      10.0.0.1' | awk '{print $1}'                                                                                                                                                                            
Ethernet0

顺便说一下,现在(以及多年来)$(cmd) 方法比

`cmd` # should be $(cmd)

for s in show ip 接口 | grep Ethernet0; do 你想要一次整行,所以你不应该迭代它。正如@Jetchisel 在简洁的评论中指出的那样,这会将字段拆分为空格并遍历每个字段。如果我没记错的话,只有一行匹配Ethernet0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多