I have text files (*.txt) which I process, I want to find words connected by hyphen such as "drug-associated" or "drug-linked", "drug-related".

I need your help to convert the first one to "associated with drug" and the second one convert it to "linked with drug" instead. In one file I could have many of those, one time it is "associated", "linked", "related" and could have other terms.

perl -pi.back -e 's/(\w+)-(\w+ed)\b/$2 with $1/g' ./*.txt

That's portable and would work with any system having perl installed.

On recent GNU systems, you can do something similar with GNU sed:

sed -ri.back 's/(\w+)-(\w+ed)\b/\2 with \1/g'


for f in ./*.txt; do
  mv -i "$f" "$f.back" &&
    sed -e :1 -e 's/\([[:alnum:]]\{1,\}\)-\([[:alnum:]]\{1,\}ed\)\(\([^[:alnum:]].*\)\{0,1\}\)$/\2 with \1\3/;t1' < "$f.back" > "$f"
  • can i do it using sed? – user2957777 May 1 '14 at 3:37

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.