Dataman
Dataman

Reputation: 3567

How to interpret the meaning of ${x%,*} and ${x#*,}

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

Answers (1)

glenn jackman
glenn jackman

Reputation: 247022

  • ${x%,*}
    • from the end of the string $x, remove the last comma and any following characters
  • ${x%%,*}
    • from the end of the string $x, remove the first comma and any following characters
  • ${x#*,}
    • from the beginning of the string $x, remove characters up to and including the first comma
  • ${x##*,}
    • from the beginning of the string $x, remove characters up to and including the last comma

I use these tricks to remember the differences:

  • on my US keyboard, # comes before %
  • ## is greedier than #

Upvotes: 2

Related Questions