Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

bash - How to remove filename prefix with a Posix shell

How can I remove the filename prefix in Bash as in the following example:

XY TD-11212239.pdf

to get

11212239.pdf

i.e, remove XY TD-?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You said POSIX shells which would include BASH, Kornshell, Ash, Zsh, and Dash. Fortunately, all of these shells do pattern filtering on variable values.

Patterns are what you use when you specify files with things like * on the Unix/Linux command line:

$ ls *.sh  # Lists all files with a `.sh` suffix

These POSIX shells use four different pattern filtering:

  • ${var#pattern} - Removes smallest string from the left side that matches the pattern.
  • ${var##pattern} - Removes the largest string from the left side that matches the pattern.
  • ${var%pattern} - Removes the smallest string from the right side that matches the pattern.
  • ${var%%pattern} - Removes the largest string from the right side that matches the pattern.

Here are a few examples:

foo="foo-bar-foobar"
echo ${foo#*-}   # echoes 'bar-foobar'  (Removes 'foo-' because that matches '*-')
echo ${foo##*-}  # echoes 'foobar' (Removes 'foo-bar-')
echo ${foo%-*}   # echoes 'foo-bar'
echo ${foo%%-*}  # echoes 'foo'

You didn't really explain what you want, and you didn't include any code example, so it's hard to come up with something that will do what you want. However, using pattern filtering, you can probably figure out exactly what you want to do with your file names.

file_name="XY TD-11212239.pdf"
mv "$file_name" "${file_name#*-}" # Removes everything from up to the first dash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...