-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
  • 97,681
  • 90
  • 411
  • 885
speedyy
  • 27
  • 5

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
  • 13,723
  • 1
  • 10
  • 37
0

You can use sed to substitute :

echo $SOMEVAR | sed 's/\ /-/g'
marxmacher
  • 591
  • 3
  • 20
  • between quotes, space don't need to be escaped! – F. Hauri - Give Up GitHub 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 - Give Up GitHub 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