babadoctor babadoctor - 2 years ago 100
Bash Question

Pipe last 11 characters in filename to a text file

  • Have a directory full of file names that end with .mp3 and have a code in it that i would like to pipe into a text file.

I need to get the last 11 characters before the .mp3 part of a file in a certain directory and pipe that into a text file (with bash on mac osx)

How do I accomplish this? With sed?

Answer Source

If I'm understanding correctly, you have a list of files with names like "abcdefghijklmnopqrstuvwxyz.mp3" and want to extract "pqrstuvwxyz". You can do this directly in bash without invoking any fancy sed business:

for F in *.mp3; do STRIP=${F/.mp3}; echo ${STRIP: -11}; done > list.txt

The first STRIP variable is the name of each file F with the .mp3 extension removed. Then you echo the last 11 characters and save to a file.

There's a nice page on bash substitutions here. sed is great but I personally find it's overkill for these simple cases.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download