Thursday, 2 February 2017

linux - Replace hyphens with underscores in bash script





Trying to write a bash script and in one part of it I need to take whatever parameter was passed to it and replace the hyphens with underscores if they exist.



Tried to do the following



#!/usr/bin/env bash
string=$1
string=${string//-/_}
echo $string;



It's telling me that this line string=${string//-/_} fails due to "Bad substitution" but it looks like it should do it? Am I missing something?


Answer



There is nothing wrong with your script, and it should work in modern versions of Bash.



But just in case you can simplify that to :



#!/bin/bash

echo "$1" | tr '-' '_'



This is in case that parameter substitution does not work ( which seems to be your case ).



Regards!


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...