3

i have a script set up to make a new directoy in folder based off a variable named for another directory that goes like this:

str="/home/folder/test"
base="$(basename $str)"

mkdir -p "/home/folder2/${base}"

What im trying to do now is find and replace a string in this varible when it makes the new folder.

Example, i have:

/Home/Album-Artist[FLAC] 

assigned to the variable. When i use mkdir to make the new directory, I want to find and replace "FLAC" with "V0" so in the new folder it will be

/Home/Album-Artist[V0]
4

Solution

Replace your line:

base="$(basename $str)"

with:

base="$(basename $str | sed 's/FLAC/V0/')"

or, if you want the [ and ] brackets to become part of the search pattern:

base="$(basename $str | sed 's/\[FLAC\]/[V0]/')"

Explanation

  • The | (or pipe) character essentially means “take the result and feed it into the next program”.

  • The sed (stream editor) command takes the input, applies commands to it, and prints the result. For example, the s/FLAC/V0/ command in sed means “for each input line, search for FLAC and replace it with V0 (but no more than once)”.

  • sed uses regular expressions instead of fixed search patterns. That means you need to escape certain characters; hence, my last example says \[ and \] in the search pattern (instead of just [ and ]).

2

In bash itself you could call sed, perl, python, swift or other languages.

If you're looking to level up in bash, try:

${var%pattern}

The % strips a pattern from the back of the variable so in one line you could srip out the ending and tack on the new.

new=${base%\[FLAC\]}"[V0]" ## [FLAC] to [V0] with \ to escape []  

More clear is the search and replace functionality assuming no artist or album would ever be FLAC and get matched. The tail end search above helps for that edge case, but is harder to read the intent.

new=${base/FLAC/V0}

You must log in to answer this question.

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