If all names contain one underscore, then just match the two parts of the name separately. You probably don't want the replacement anywhere in the line, just at the end of the file name, so lose the g
modifier.
ls | sed 's/^\(.*\)_\(.*\)\.png$/\1_\2\/\1\2,/'
By the way, ls -1
is equivalent to ls
when not used interactively. ls *
is not equivalent to ls
, the main difference being that if the current directory contains subdirectories then ls
lists the entries in the current directory whereas ls *
lists the entries that aren't subdirectories plus the content of all subdirectories. Given that this is hardly ever useful, you presumably meant ls
.
If you want to remove all underscores no matter how many there are, while it's possible to use sed, it's rather clearer in awk.
ls | awk 'sub(/\.png$/, "") {$0 = $0 "/" gsub(/_/, "", $0) ","} 1'
Alternatively, you can use a shell loop.
for x in *; do
case $x in
*.png) x=${x%.png}; printf '%s/\n' "$x"; printf '%s,\n' "$x" | tr -d _;;
esac
done
ls| sed '/\.png$/!d;s///;h;s/_//g;H;g;s|\n|/|;s/$/,/'
. – Guuk Jan 20 '15 at 13:48