Announcement

Collapse
No announcement yet.

A simple Bash script for replacing all space characters in a string

Collapse
This topic is closed.
X
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    A simple Bash script for replacing all space characters in a string

    I had use for this today and decided to share it in case someone else needs something similar.

    Code:
    #!/bin/bash
    
    count=0
    name=""
    
    for word in $@
    do
        if [ $count -ge 1 ]
        then
            name+="_" # replacement character
        fi
        name+="$word"
        count=$((count + 1))
    done
    echo "$name"
    Example:

    Code:
    $ ./repspc Space the final frontier
    Space_the_final_frontier
    This script has not been heavily tested so think twice about using it for mission critical applications. Please do add your comments, criticisms and improvements below.
    Welcome newbies!
    Verify the ISO
    Kubuntu's documentation

    #2
    Re: A simple Bash script for replacing all space characters in a string

    Somebody said: "People who don't know UNIX are condemned to reinvent it... badly. "

    tr " " "_"

    Code:
    echo "This is a test" | tr " " "_"
    or

    Code:
    cat filename | tr " " "_"

    Comment


      #3
      Re: A simple Bash script for replacing all space characters in a string

      Indeed, tr is one of many possible ways to solve the problem. But it is not a Bash script, nor is tr internal to Bash.

      I wouldn't ever dream of calling what I did inventive either. I'm well aware that any programing problem I want to solve has already been solved better than I can do. That doesn't stop me from finding my own solutions in ways that work for me.
      Welcome newbies!
      Verify the ISO
      Kubuntu's documentation

      Comment

      Working...
      X