1

I have a string with 3 fields separated by whitespace. I would like to concat the 2 last fields with - making sure that the newline in the end is removed.

The following works:

echo -n "abc 1234 5679" | tr -s "" |cut -d ' ' -f2 -f3 | tr " " "-"  

I was wondering if there is a perl onliner for this?

  • 2
    Why do you need perl for this?. There is no new line character in your string shown – Inian Mar 29 '18 at 9:00
  • If you're happy with one or several of the answers, upvote them. If one is solving your issue, accepting it would be the best way of saying "Thank You!" Accepting an answer also indicates to future readers that the answer actually solved the problem. – Kusalananda Apr 8 '18 at 11:30
2

Using awk:

printf 'abc 1234 5679' | awk '{printf "%s", $2"-"$3}'

or perl's awk mode (-a):

printf 'abc 1234 5679' | perl -ape '$_ = "$F[1]-$F[2]"'

Note that both would remove the line delimiter if present, if you want to preserve it if it's there, with GNU awk:

printf 'abc 1234 5679\n' | gawk '{printf "%s", $2"-"$3 RT}'

With perl:

printf 'abc 1234 5679\n' | perl -ape 's/.*/$F[1]-$F[2]/'
  • I want to be sure that the new line delimiter and possibly any trailing whitespace removed – Jim Mar 29 '18 at 19:02
2

Use this :

$ echo -n "abc 1234 5679" | perl -pe 's/(\d+)\s+(\d+)$/$1-$2/' 

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.