将第三个单词与第二个单词开头的 20 个空格对齐

将第三个单词与第二个单词开头的 20 个空格对齐

我们有以下文件:

cat info.txt

linux03.sys98.com net16777728       Speed: 1000Mb/s
linux03.sys98.com net16777728       Speed: 1000Mb/s
linux01.sys98.com net3f0    Speed: 1000Mb/s
linux01.sys98.com net3f0    Speed: 1000Mb/s

linux03.sys98.com net16777728       Duplex: Full
linux03.sys98.com net16777728       Duplex: Full
linux01.sys98.com net3f0    Duplex: Full
linux01.sys98.com net3f0    Duplex: Full

linux04.sys98.com net3f2    Link detected: no
linux04.sys98.com net3f3    Link detected: no

linux04.sys98.com net3f2    Speed: Unknown!
linux04.sys98.com net3f3    Speed: Unknown!

linux04.sys98.com net3f2    Duplex: Unknown! (255)
linux04.sys98.com net3f3    Duplex: Unknown! (255)

linux03.sys98.com net16777728       Link detected: yes
linux03.sys98.com net16777728       Link detected: yes
linux01.sys98.com net3f0    Link detected: yes
linux01.sys98.com net3f0    Link detected: yes

我们希望将第三个单词与第二个单词开头的 20 个空格对齐,如下预期结果:

linux03.sys98.com net16777728          Speed: 1000Mb/s
linux03.sys98.com net16777728          Speed: 1000Mb/s
linux01.sys98.com net3f0               Speed: 1000Mb/s
linux01.sys98.com net3f0               Speed: 1000Mb/s

linux03.sys98.com net16777728          Duplex: Full
linux03.sys98.com net16777728          Duplex: Full
linux01.sys98.com net3f0               Duplex: Full
linux01.sys98.com net3f0               Duplex: Full

linux04.sys98.com net3f2               Link detected: no
linux04.sys98.com net3f3               Link detected: no

linux04.sys98.com net3f2               Speed: Unknown!
linux04.sys98.com net3f3               Speed: Unknown!

linux04.sys98.com net3f2               Duplex: Unknown! (255)
linux04.sys98.com net3f3               Duplex: Unknown! (255)

linux03.sys98.com net16777728          Link detected: yes
linux03.sys98.com net16777728          Link detected: yes
linux01.sys98.com net3f0               Link detected: yes
linux01.sys98.com net3f0               Link detected: yes

如何使用 printf 或任何其他解决方案执行此操作?

答案1

perl

perl -ne 'printf "%s %-20s %s\n", /(\S+\s+)(\S+)\s*(.*)/' your-file

或者避免接触与该模式不匹配的线:

perl -pe '$_ = sprintf "%s %-20s %s\n", $1, $2, $3
            if /(\S+\s+)(\S+)\s*(.*)/' your-file

答案2

使用sed,您可以在第二个字段之后添加大量空格,然后删除第 20 个字符之后的所有内容:

sed -E 's/([^ ]* ){2}/&                   /;s/( .{20}) */\1/'

答案3

使用 bash,你可以写

while read a b rest; do
    printf "%s %-20s %s\n" "$a" "$b" "$rest"
done < info.txt

相关内容