ABC
ABC

Reputation: 718

Bash splitting filename with space and dash in delimiter

I have a bunch of files that I have been able to get with the following command (where EXT is the extension):

oIFS=$IFS
IFS=$'\n'

array=$(find . -iregex '.*\(EXT\)' -print)
for file in ${array[@]}; do
    echo "$file"| cut -f1 -d" - "
done

IFS=oIFS

The file name format is like so: PARTONE - PARTTWO where part one is any character (but not a dash [-], and part two is any character and can include a dash)

Is there any way to get PARTONE and PARTTWO into their own variables? Currently, (I believe that) due to the space being part of the delimiter it doesn't work and I get the following error cut: bad delimiter

Upvotes: 0

Views: 3106

Answers (1)

lurker
lurker

Reputation: 58284

Here is one of many ways:

oIFS=$IFS
IFS=$'\n'

array=$(find . -iregex '.*\(EXT\)' -print)
for file in ${array[@]}; do
    PART_ONE=`echo $file | sed "s/ - .*$//"`
    PART_TWO=`echo $file | sed "s/^[^-]* - //"`
done

IFS=$oIFS

To remove a ./ prefix from the first part (assuming one always exists):

PART_ONE=`echo $file | sed "s/^\.\/\([^-]*\) - .*$/\1/"`

And to remove an extension from the second part:

PART_TWO=`echo $file | sed "s/^[^-]* - \(.*\)\.[^\.]*$/\1/"`

Upvotes: 1

Related Questions