Cameron
Cameron

Reputation: 2965

Using sed substitution, how can I add spaces at the end?

I want to insert a space in the middle so that the string

up 2 days, 12:32

becomes

up 2 days,  12:32

I've been trying to do this using sed substitution. My sed function looks like

sed 's/,/, /'

And I feel like that should work, but trailing whitespaces are being ignored.

I've tried using '\' to see if I could escape whitespaces. I'm not sure what's going on because spaces before the comma aren't being discarded. I feel like this is asked a lot, but I haven't found anything that works for me.

EDIT: This is the full command that I call sed in

echo "    "`uptime | cut -d ' ' -f3-6 | sed 's/,$//' | sed 's/,/, /'`

I expect the output to be

up 2 days,  12:32

but instead I got

up 2 days, 12:32

Upvotes: 1

Views: 190

Answers (3)

Bach Lien
Bach Lien

Reputation: 1060

As @Jerry suggestion, put backticks inside double quotes:

echo "    `uptime | cut -d ' ' -f3-6 | sed 's/,$//' | sed 's/,/, /'`"

As @tripleee suggestion, here is a shorter solution, sed called once:

uptime|sed 's:,  .*$::;s:, :,  :;s:^.*up:    up:'
            ^          ^         ^
            |__________|_________|___ s:,*  .*$::     remove ',  ' (2 spaces) to end
                       |_________|___ s:, :,  :       add one space after ','
                                 |___ s:^.*up:    up: add spaces before 'up'

It works with both single day, or multiple days. Test:

$ a=' 12:02:45 up  1:09,  1 user,  load average: 0.06, 0.13, 0.16'
$ b=' 12:02:45 up  2 days, 20:30,  1 user,  load average: 0.06, 0.13, 0.16'
$ sed 's:,  .*$::;s:, :,  :;s:^.*up:    up:' <<<"$a"
     up  1:09
$ sed 's:,  .*$::;s:, :,  :;s:^.*up:    up:' <<<"$b"
     up  2 days,  20:30

Upvotes: 2

David C. Rankin
David C. Rankin

Reputation: 84521

You can do it with a single call to sed and backreferences if you like, e.g.

$ uptime | 
sed 's/^[^u]*\(up [0-9][0-9]* days*\)[^0-9]*\([0-9][0-9]*:[0-9][0-9]\).*$/\1,  \2/'
up 1 day,  11:02

or a machine with multiple days (same regex):

$ uptime | 
sed 's/^[^u]*\(up [0-9][0-9]* days*\)[^0-9]*\([0-9][0-9]*:[0-9][0-9]\).*$/\1,  \2/'
up 134 days,  4:19

The basic regex simply locates up digits day(s) and then the hours:minutes (captured as backreference \1 and \2) and then forms the final substitution with \1, \2 (you can enter as many (or few) spaces as you like)

Upvotes: 0

Guy
Guy

Reputation: 647

Maybe keep everything simple - why does it have to be echoed when sed or awk will output to stdout anyway? This is using the output of GNU uptime - i don't know whether it varies at all though, so may need tweaking

uptime | 
awk '{ 
  printf "%s %s %s,  %s\n", $2, $3, $4, substr($5,0,5) 
}'

You may want to correct the formatting as well, to add some spaces at the start

Upvotes: 1

Related Questions