Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the file suffix and path portion from a path string in Bash?

Given a string file path such as /foo/fizzbuzz.bar, how would I use bash to extract just the fizzbuzz portion of said string?

like image 552
Lawrence Johnston Avatar asked Sep 24 '08 03:09

Lawrence Johnston


People also ask

How do I remove a file extension from a string in bash?

Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.

How do I remove something from a string in bash?

Remove Character from String Using cut Cut is a command-line tool commonly used to extract a portion of text from a string or file and print the result to a standard output. You can also use this command for removing characters from a string.


1 Answers

Here's how to do it with the # and % operators in Bash.

$ x="/foo/fizzbuzz.bar" $ y=${x%.bar} $ echo ${y##*/} fizzbuzz 

${x%.bar} could also be ${x%.*} to remove everything after a dot or ${x%%.*} to remove everything after the first dot.

Example:

$ x="/foo/fizzbuzz.bar.quux" $ y=${x%.*} $ echo $y /foo/fizzbuzz.bar $ y=${x%%.*} $ echo $y /foo/fizzbuzz 

Documentation can be found in the Bash manual. Look for ${parameter%word} and ${parameter%%word} trailing portion matching section.

like image 78
Zan Lynx Avatar answered Sep 23 '22 17:09

Zan Lynx