質問

I have a title that has 5 consecutive dots which I'd like replaced with just one space using bash script. Doing this is not helping:

tr '.....' ' ' 

Obviously because it's replacing the five dots with 5 spaces.

Basically, I have a title that I want changed to a slug. So I'm using:

tr A-Z a-z | tr '[:punct:] [:blank:]' '-'

to change everything to lowercase and change any punctuation mark and spaces to a hyphen, but I'm stuck with the dots.

The title I'm using is something like: Believe.....Right Now

So I want that turned into believe-right-now

How do I change the 5 dots to a single space?

役に立ちましたか?

解決

You don't need sed or awk. Your original tr command should do the trick, you just need to add the -s flag. After tr translates the desired characters into hyphens, -s will squeeze all repeated hyphens into one:

tr A-Z a-z | tr -s '[:punct:] [:blank:]' '-'

I'm not sure what the input/output context is for you, but I tested the above as follows, and it worked for me:

tr A-Z a-z <<< "Believe.....Right Now" | tr -s '[:punct:] [:blank:]' '-'

output:

believe-right-now

See http://www.ss64.com/bash/tr.html for reference.

他のヒント

Transliterations are performed with mappings, which means each character is mapped into something else -- or delete, with tr -d. This is the reason why tr '.....' ' ' does not work.

Replacing five dots with space:

  • using sed with extended regular expressions:

    $ sed -r 's/\.{5}/ /g' <<< "Believe.....Right Now"
    Believe Right Now
    
  • using sed without -r:

    $ sed 's/\.\{5\}/ /g' <<< "Believe.....Right Now"
    Believe Right Now
    
  • using parameter expansion:

    $ text="foo.....bar.....zzz" && echo "${text//...../ }"
    foo bar zzz
    

Replacing five dots and spaces with -:

$ sed -r 's/\.{5}| /-/g' <<< "Believe.....Right Now"
Believe-Right-Now

Full replacement -- ditching tr usage:

$ sed -re 's/\.{5}| /-/g' -e 's/([A-Z])/\l&/g' <<< "Believe.....Right Now"
believe-right-now

or, in case your sed version does not support the flag -r, you may use:

$ sed -e 's/\.\{5\}\| /-/g' -e 's/\([A-Z]\)/\l&/g' <<< "Believe.....Right Now"
believe-right-now
$ cat file
Believe.....Right Now

$ awk '{gsub(/[[:punct:][:space:].]+/,"-"); print tolower($0)}' file
believe-right-now
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top