-1
read -p "enter some words :" $PASTE

curl -s "example.com/${PASTE} | code continues

What I want to do is if user enter two or more words I want to substitute spaces with - in PASTE variable.

Example:

PASTE=default application

New paste:

PASTE=default-application

How can I do that?

jww
  • 90,984
  • 81
  • 374
  • 818
speedyy
  • 27
  • 5
  • `PASTE=$(echo $PASTE | tr "\n" " ")` – duyue Dec 21 '19 at 08:01
  • 1
    Does this answer your question? [Replace one character with another in Bash](https://stackoverflow.com/questions/5928156/replace-one-character-with-another-in-bash) – Léa Gris Dec 21 '19 at 09:35
  • Consider `-r` option of `read` command, then `-G -I` to `curl` for testing URL before *code continues*! – F. Hauri Dec 21 '19 at 09:45

2 Answers2

1

See below, using the '/' modifier to replace ' ' with '-'. Notice typo fix in 'read' command:

    # Notice no '$' for PASTE.
read -p "enter some words :" PASTE
    # Replace ALL ' ' with '-'
PASTE=${PASTE// /-}
curl -s "website.com/${PASTE} | code continues
dash-o
  • 12,431
  • 1
  • 6
  • 32
0

You can use sed to substitute :

echo $SOMEVAR | sed 's/\ /-/g'
marxmacher
  • 552
  • 3
  • 19
  • between quotes, space don't need to be escaped! – F. Hauri Dec 21 '19 at 08:59
  • `sed` is a bit overrkill compared to `tr`. `SOMEVAR="some word"; SOMEVAR="$(printf "$SOMEVAR" | tr '[:space:]' '-')"; echo "$SOMEVAR"` – Léa Gris Dec 21 '19 at 09:00
  • @LéaGris using [tag:bash], `tr` is overkill too, [dash-o's answer](https://stackoverflow.com/a/59434545/1765658) solution using `${var// /-}` is more efficient. – F. Hauri Dec 21 '19 at 09:35
  • @F.Hauri I guess only because `tr` is an external program that takes long to start. The actual search-and-replace procedure in bash seems to be tremendously slow. See [my comment on the linked duplicate](https://stackoverflow.com/questions/5928156/replace-one-character-with-another-in-bash#comment105055999_5928254). – Socowi Dec 21 '19 at 11:18