9

Is there a simple command line to extract the last part of a string separated by hyphens? E.g., I want to extract 123 from foo-bar-123.

21

You can use Bash's parameter expansion:

string="foo-bar-123" && printf "%s\n" "${string##*-}"
123

If you want to use another process, with Awk:

echo "foo-bar-123" | awk -F- '{print $NF}'

Or, if you prefer Sed:

echo "foo-bar-123" | sed 's/.*-//'

A lighter external process, as Glenn Jackman suggests is cut:

cut -d- -f3 <<< "$string"
  • shell parameter expansion is the best answer. A lightweight external tool is cut: cut -d- -f3 <<< "$string" – glenn jackman Mar 31 '15 at 1:17
  • 1
    @glennjackman - re: cut; indeed but only if the number of the last field is known (as the question is a bit ambiguous: Is there a simple command line to extract the last part... ? ) – don_crissti Mar 31 '15 at 1:28
  • 2
    @don_crissti, indeed. One could do rev <<< "$string" | cut -d- -f1 | rev, but then we're veering away from the simplicity of param.expansion. – glenn jackman Mar 31 '15 at 2:10
3
grep -Po '(?<=\w-)\w+(?=$|[\s.,])'
1
echo "foo-bar-123"| awk -F"-" '{print $3}' 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.