Reputation: 17640
I have files that are named like C1_1_B_(1)IMG1511.jpg
and I want to split them up into a list where i get back as
C1
1
B
(1)
IMG1511.jpg
trying to figure out if i need to do this with sed
or awk
or regex
or even what that would look like i could do it in applescript but I would rather call shell command as it is much faster
EDIT
Ok so now its changed a bit and I can figure out how to fix it
example are
"P24-M_(1)Lighter_Ray_Logo_Full_Color.jpg"
"P24_(1)24x36loren.jpg"
so _(*) indicates where I want to stop listing so i end up with
P24
M
(1)
Lighter_Ray_Logo_Full_Color.jpg
and
P24
(1)
24x36loren.jpg
Upvotes: 0
Views: 385
Reputation: 11
I know it's not sed/awk, but here's something that would work in perl:
#!/usr/bin/perl
while(<STDIN>) {
my($line) = $_;
chomp($line);
my @values = split(/_|(\(\d+\))/, $line);
foreach my $val (@values) {
if ( $val !~ m/^$/)
{
print "$val\n";
}
}
}
exit 0;
Upvotes: 1
Reputation: 246764
str="C1_1_B_(1)IMG1511.jpg"
ary=( $(IFS=_; echo $str) )
for ((idx=0; idx < ${#ary[@]}; idx++)); do echo ${ary[$idx]}; done
outputs
C1
1
B
(1)IMG1511.jpg
Upvotes: 0
Reputation: 58371
Would this do?
<<<"C1_1_B_(1)IMG1511.jpg" sed -r 'y/_/\n/;s/\([^)]*\)/&\n/g;'
Upvotes: 1
Reputation: 6856
This handles filenames which contain _ ( )
in other places.
<<< '
C1_1_B_(1)IMG151).jpg
C1_1_B_(1)IMG_(4444).jpg
C(22)2_1_22_333_B_(144)I_M_G_(_1511).jpg
' sed -nr '# isolate, process and print first section
s/^([^(]+)_/\1\n/;h
s/(.*)\n.*/\1/
s/([^_]+)_/\1\n/gp;x
# process the second section
s/.*\n(.*)/\1/
s/([^)]+\))/\1\n/p
';exit
Upvotes: 0
Reputation: 424993
Translate _
to new lines:
echo "C1_1_B_(1)IMG1511.jpg" | tr '_' '\n'
Output:
C1
1
B
(1)IMG1511.jpg
Although, it looks like you want to split on )
as well. No can do with tr
, but...
echo "C1_1_B_(1)IMG1511.jpg" | tr '_' '\n' | sed -e 's/)/)\
/'
There's a linefeed inside the replacement string, which is needed for Mac. On other *nix OS's, a simple escape works:
echo "C1_1_B_(1)IMG1511.jpg" | tr '_' '\n' | sed -e 's/)/)\n/'
Output:
C1
1
B
(1)
IMG1511.jpg
Upvotes: 5
Reputation: 956
If the filename is stored in $P, the following works with zsh:
myarr=${(s/_/)$(echo $P | sed 's/)/)_/g')}
This creates an actual array.
Upvotes: 0