3

I have around 200 filenames that I am trying to pull data from. The format is something along the lines of: filename(120516.1108).mp3 I am trying to pull the part before the "(" and also the part before the ".". Not all of the files have this format either so theres an extra challenge.

The output should be : "filename" "120516"

I am wanting to perform this operation in bash if at all possible. I am still learning and have very little experience in bash. Any explanations along with code is very welcome.

  • 2
    To clarify the question please add what the output should be at your example. – ADDB May 31 '17 at 13:42
  • Added an example of the output. – John Smith May 31 '17 at 13:51
0

If I understand correctly that command should work(if there are no '(' and '.' In the filename)

data=$(echo $file | cut -d"." -f1 | tr -d "(")

Split them into 2 variables:

filename=$(echo $file | cut -d"(" -f1)
number=$(echo $file | cut -d"(" -f2 | cut -d"." -f1)
  • When ran I received a missing operand error: tr: missing operand after ‘(’ Two strings must be given when translating. – John Smith May 31 '17 at 14:00
  • Sorry I forgot the -d for delete after tr – ADDB May 31 '17 at 14:02
  • It works! Is there any way to split the result into two different data segments? – John Smith May 31 '17 at 14:06
  • Like what? Describe/Give an example – ADDB May 31 '17 at 14:06
  • Split the "filename" and "120516" into two different variables. Like f = "filename" and d = "120516" ? – John Smith May 31 '17 at 14:09
3

"in bash", something like:

re='^(.*)\(([0-9]+)\.[0-9]+\).*$'

Then

for f in *.mp3; do 
  [[ $f =~ $re ]] && printf '"%s" "%s"\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
done
1

Use parameter expansion truncation.

case "$filename" in
  *\(*.*\)*)
    before_first_parenthesis=${filename%%\(*}
    after_first_parenthesis=${filename#*\(}
    before_dot=${after_first_parenthesis%%.*}
    echo "$before_first_parenthesis" "$before_dot"
  *) echo "does not match the format";;
esac

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.