VeLKerr
VeLKerr

Reputation: 3157

Replacement substring in shell input

I get the set of strings as input in terminal. I need to replace the ".awk" substring to ".sh" in each string using shell and then output modified string. I wrote such script for doing this:

#!/bin/bash

while read line
do
  result=${line/.awk/.sh}
  echo $result
done

But it gives me an error: script-ch.sh: 6: script-ch.sh: Bad substitution.

How should I change this simple script to fix error?

UPD: ".awk" may be inside the string. For example: "file.awk.old".

Upvotes: 0

Views: 96

Answers (3)

Vitaly Sementsov
Vitaly Sementsov

Reputation: 1

If you run chmod +x script.sh and then run it with ./script.sh, or if you run it with bash script.sh, it should work fine.

Running it with sh script.sh will not work because the hashbang line will be ignored and the script will be interpreted by dash, which does not support that string substitution syntax.

Upvotes: 0

David C. Rankin
David C. Rankin

Reputation: 84551

If you are using Bash, then there is nothing wrong with your substitution. There is no reason to spawn an additional subshell and use a separate utility when bash substring replacement was tailor made to do that job:

$ fn="myfile.awk.old"; echo "$fn  -->  ${fn/.awk/.sh}"
myfile.awk.old  -->  myfile.sh.old

Note: if you are substituting .sh for .awk, then the . is unnecessary. A simple ${fn/awk/sh} will suffice.

I suspect you have some stray DOS character in your original script.

Upvotes: 3

Mike Furlender
Mike Furlender

Reputation: 4019

Not sure why it works for you and not for me.. might be the input you're giving it. It could have a space in it.

This should work:

#!/bin/bash

while read line
do
  result=$(echo $line | sed 's/\.awk/\.sh/')
  echo $result
done

Upvotes: 2

Related Questions