sed Removing whitespace around certain character

2019-07-17 08:58发布

what would be the best way to remove whitespace only around certain character. Let's say a dash - Some- String- 12345- Here would become Some-String-12345-Here. Something like sed 's/\ -/-/g;s/-\ /-/g' but I am sure there must be a better way.

Thanks!

3条回答
Anthone
2楼-- · 2019-07-17 09:32

If you mean all whitespace, not just spaces, then you could try \s:

echo 'Some- String- 12345- Here' | sed 's/\s*-\s*/-/g'

Output:

Some-String-12345-Here

Or use the [:space:] character class:

echo 'Some- String- 12345- Here' | sed 's/[[:space:]]*-[[:space:]]*/-/g'

Different versions of sed may or not support these, but GNU sed does.

查看更多
Bombasti
3楼-- · 2019-07-17 09:36

Try:

's/ *- */-/g'
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-07-17 09:43

you can use awk as well

$ echo 'Some   - String-    12345-' | awk -F" *- *" '{$1=$1}1' OFS="-"
Some-String-12345-

if its just "- " in your example

$ s="Some- String- 12345-"
$ echo ${s//- /-}
Some-String-12345-
查看更多
登录 后发表回答