1
  • 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?

Noble
  • 51
  • 10

2 Answers2

3

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.

jonthalpy
  • 1,042
  • 8
  • 22
  • 2
    It can be done with `${mavar: -15:11}`, and it worth mentioning that it's from Bash 4.2. – SLePort May 21 '16 at 06:44
  • Good call. I was actually playing with to see if I could reduce it to a single substitution and avoid the temporary variable. I don't think it can get more straightforward than that! – jonthalpy May 21 '16 at 06:47
  • Wow! you guys sure do know a lot about bash! :) thanks! – Noble May 21 '16 at 06:55
  • Don't use all upper case for non-exported variable names and always quote your variables (google is your friend). `for f in *.mp3; do strip="${f/.mp3}"; echo "${strip: -11}"; done > list.txt` – Ed Morton May 21 '16 at 14:06
1

Along with good above answers, can be done via awk

for f in `ls *.mp3`;
echo  $f|awk -F. '{printf substr($1,length($1)-11,length($1)),$2;}'
done
sumitya
  • 2,631
  • 1
  • 19
  • 32