Reputation: 3567
Problem formulation:
let's say I have a file called pairs.tsv
where each line contains a comma separated pair of, for instance, paths to files:
% cat pairs.tsv
path1,path2
path3,path4
The following code iterates through each line and splits it where the comma
occurs and then echos each result of the split.
for line in $(cat pairs.tsv); do
echo ${line%,*}
echo ${line#*,}
% returns:
path1
path2
path3
path4
I would like to know the meaning behind these ${x%,*}
and ${x#*,}
; especially %,*
and #*,
part. I know what they do, but I don't know how they do it! And what these special characters are called!
The reason that I am interested to understand how this is down, is to be able to replicate the same logic in other situations. Therefore, any kind of hint is greatly appreciated.
Thanks in advance! :)
Upvotes: 0
Views: 270
Reputation: 247022
${x%,*}
$x
, remove the last comma and any following characters${x%%,*}
$x
, remove the first comma and any following characters${x#*,}
$x
, remove characters up to and including the first comma${x##*,}
$x
, remove characters up to and including the last commaI use these tricks to remember the differences:
#
comes before %
##
is greedier than #
Upvotes: 2