문제

I have trouble for renaming filename in bash.

My filename pattern is like this:

"sometext pattern trashtext.ext"

I want to keep sometext and replace pattern and trashtext by something else. The sometext has variable length and may be containing space, the pattern is unique, and trashtext has variable length and may contain special char like '[' which are note handled well with sed. "sometext pattern trashtext.ext" => "sometext myreplacement"

I have found a solution but I suppose there's a better way: Get rid of the special char in trashtext:

rename 'y/\[/ /' *.ext

Get the part to remove:

var=$(ls | grep -Po 'pattern[^/]+')

Remove it with sed:

sed "s/$var/blabla/"

Thanks for your help

도움이 되었습니까?

해결책

Try like this:

pattern=somepattern
replacement=somereplacement
ext=ext
rename "s/$pattern.*?\.$ext$/$replacement.$ext/" *.$ext

The .*? should match your "trashtext" in between the pattern and the extension, and replace it with the replacement. It doesn't matter if trashtext contains special characters.

If, as the replacement you want to use whatever was matched by the pattern, you can do like this:

rename "s/($pattern).*?\.$ext$/\$1.$ext/" *.$ext

Finally, it's best to use the -n flag while playing with the syntax. This way the command will just show what it would do instead of really doing it:

rename -n "s/($pattern).*?\.$ext$/\$1.$ext/" *.$ext

다른 팁

Using bash parameter expansion

f="sometext pattern trashtext.ext"
prefix=${f%% pattern*}
ext=${f##*.}
echo $prefix.$ext
sometext.ext
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top