0

We have the following file:

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

We want to align the third word with 20 spaces from the beginning of the second word as the following expected results:

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

How to perform that with printf or any other solution?

valiano
  • 649
jango
  • 423

3 Answers3

2

With perl:

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

Or to avoid touching lines that don't match that pattern:

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

With sed, you would add lots of spaces after the second field and then remove everything after the 20th char:

sed -E 's/([^ ]* ){2}/&                   /;s/( .{20}) */\1/'
Philippos
  • 13,453
0

With bash, you would write

while read a b rest; do
    printf "%s %-20s %s\n" "$a" "$b" "$rest"
done < info.txt
glenn jackman
  • 85,964