简体   繁体   中英

Bash Script: Difference between %% and //

To remove all characters after a specific string in bash, I found out that there are two ways of doing it, either using the // or %%.

For example, if I want to rename files that have the format "This is the 505 file of a total of 83018 files". I can rename them by removing everything after the "of" string so that it is only named "This is the 505 file" using these 2 ways.

newfilename=${filename//of*}

and

newfilename=${filename%%of*}

Both of these when run, removes all characters after the "of" string.

I am wondering whats the difference between using %% and // when removing parts of a string and if there are cases when I should be using one over the other.

Thanks

They are two different functions

${string//find/replace}

${string%%pattern}

eg

$ var="here of there of"; echo ${var//of}
here there

if you don't provide replacement string, it's a simple delete

$ var="here of there of"; echo ${var%%of}
here of there

this takes the longest substring matching the pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM