Quantcast
Viewing latest article 1
Browse Latest Browse All 2

Answer by Zanna for Convert output of shell script to .csv

Well, looks like we can do it with sed :)

This looks OK to me (the leading | is me assuming you'll be piping the output of your script into the command):

| sed -r '/test/ N;N;N; s/(.*)\n([A-Za-z]*)\s*(.*)\n(.*)\n.*/\1  \2 \3  \4/'
test-tch008.test.com  rsyslog Mon 16 Jul 2018 04:36:50 AM EDT   02:18:20 up 953 days,  8:16,  1 user,  load average: 0.08, 0.06, 0.08
test-twh005.test.com  rsyslog Mon 16 Jul 2018 04:37:08 AM EDT   02:18:21 up 1750 days, 13:38,  1 user,  load average: 0.07, 0.14, 0.17
test-vch108.test.com  rsyslog Mon 16 Jul 2018 04:38:55 AM EDT   02:18:23 up 94 days,  1:33,  1 user,  load average: 0.30, 0.28, 0.27
test-vch109.test.com  rsyslog Mon 16 Jul 2018 04:39:03 AM EDT   02:18:25 up 31 days,  1:22,  1 user,  load average: 0.18, 0.10, 0.08

But if you want to put that header line in... well I can only think of this ugly way...

| sed -r '1 s/^/servername            patch history                             uptime\n/; /test/ N;N;N; s/(.*)\n([A-Za-z]*)\s*(.*)\n(.*)\n.*/\1  \2 \3  \4/'
servername            patch history                             uptime
test-tch008.test.com  rsyslog Mon 16 Jul 2018 04:36:50 AM EDT   02:18:20 up 953 days,  8:16,  1 user,  load average: 0.08, 0.06, 0.08
test-twh005.test.com  rsyslog Mon 16 Jul 2018 04:37:08 AM EDT   02:18:21 up 1750 days, 13:38,  1 user,  load average: 0.07, 0.14, 0.17
test-vch108.test.com  rsyslog Mon 16 Jul 2018 04:38:55 AM EDT   02:18:23 up 94 days,  1:33,  1 user,  load average: 0.30, 0.28, 0.27
test-vch109.test.com  rsyslog Mon 16 Jul 2018 04:39:03 AM EDT   02:18:25 up 31 days,  1:22,  1 user,  load average: 0.18, 0.10, 0.08

Explanation

  • -r Use extended regex - saves a few backslashes
  • s/old/new/ replace old with new
  • 1 s/^/literally what I want to insert\n/ replace the start of the first line with your header line, ending with a new line. Luckily, sed interprets \n as a newline in this context.
  • /test/ find a line with test
  • N;N;N read the next three lines in too, so we can use \n in the regex and process all three lines
  • (.*) save any number of any characters (save the whole line)
  • ([A-Za-z]) save a bunch of letters (this is rsyslog, so you could just write rsyslog if it's always the same).
  • \s horizontal whitespace
  • \1 \2 \3 \4 The saved patterns, with the correct spacing.

Viewing latest article 1
Browse Latest Browse All 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>