(regex,sed) How to append erased word after erasing word

62 Views Asked by At

What I want to change

.:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:.:/sbin:/bin  

What I want to make

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.  

I want to pick up all dots ("."), and Want to append to end of the line.
If there is no dot (".") in the line, Then It just print the line.

I can erase dot in the line which have dots. But I can't append dot to end of the line under this condition (/\.:/).

$ echo /usr/local:.:/bin | sed -r -e "/\.:/s/(\.:)//g"

How can I append erased word after I erase word, only with the sedcommand?

2

There are 2 best solutions below

4
Wiktor Stribiżew On BEST ANSWER

You can use

#!/bin/bash
s='.:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:.:/sbin:/bin'
sed -r -e 's/(.+)\.:/.:\1/' -e 's/(.)\.:/\1/g' -e 's/\.:(.+)/\1:./' <<< "$s"
# => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:.  

See the online demo

Here,

  • s/(.+)\.:/.:\1/ finds a .: substring anywhere in your string and move the .: found to the start of the string
  • s/(.)\.:/\1/g removes all non-initial .: char combinations in the string and then
  • s/^\.:(.+)/\1:./ removes the .: at the start of the string and pastes :. at the end.
0
Amessihel On

You can append another expression to sed: -e "s/:?$/:./".

That means: replace the end of line (and any eventual trailing colon) by a dot.