So I am writing a program in bash involving a madlibs and I have to create a function that replaces the first occurence of a word for example. If the first word inputted was apple I can use this function to replace it with pear. How would I go about that in bash? (Very new to bash)

function replaceFirst(){
#Code to go here 


I saw some things about "sed" but as I said I am new so any help would be great!

  • 1
    Please provide example input and output texts (not just one keyword) Nov 27, 2023 at 7:52
  • 2
    "I saw some things about "sed"" - what did you see and what did you try? Nov 27, 2023 at 7:52

1 Answer 1


To replace one word with another, there is no need to use external commands like sed. Bash itself can do the job.

function replace_first {
    local user_input="$1"
    local replace_with="$2"

    set -f -- $1
    local first_word="$1"

    echo "${user_input/#$first_word/$replace_with}"

# read user input
read -rp 'Enter some text: '

# sample usage
replace_first "$REPLY" Hello

set re-sets the positional parameters, so you can easily access the first word of the user's input. The -f option prevents filename expansion. Also note that $1 is not quoted. In general, you should always quote your variables, but in this case word splitting is desired.

${parameter/#pattern/string} replaces only the first word of the string. This is in case the same word occurs elsewhere in the string.

Bash provides detailed information about Shell Parameter Expansion.

Let's say the input text is Hi there. The output would look like this:

$ Enter some text: Hi there
Hello there

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .