1

I want to copy the line containing www.website.com into the line containing thetext.

For example, I want to transform this input:

Lorem ipsum dolor sit amet, elit.
Cras eu www.website.com velit vitae
Pellentesque interdum
thetext
Sed ullamcorper tellus

into this output:

Lorem ipsum dolor sit amet, elit.
Cras eu www.website.com velit vitae
Pellentesque interdum
thetextCras eu www.website.com velit vitae
Sed ullamcorper tellus

I have no idea how to copy-paste using sed. It looks somewhat tricky.

2 Answers 2

2

You may also use ed (here used in the Bash shell) to move & join lines as follows:

str='
Lorem ipsum dolor sit amet, elit.
Cras eu www.website.com velit vitae
Pellentesque interdum
thetext
Sed ullamcorper tellus
'

# cf. http://wiki.bash-hackers.org/howto/edit-ed
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$str")
   H
   /www\.website\.com/m/thetext/
   -1,.j
  ,p
  q
EOF

If you're going to edit files in-place, ed may be your tool of choice.

1

I'm not sure if that's exactly what you want, but:

  1. When you see the interesting line (the line containing www.website.com), copy it into the hold space.
  2. When you see the text to replace (thetext), append the contents of the hold space, and
  3. clean up the result.
sed -e '/www\.website\.com/h' \
    -e '/thetext/{' -e 'G' -e 's/\n//' -e '}'

I do recommend turning to awk for anything beyond a plain s///.

awk '
    /www\.website\.com/ { line=$0 }
    /thetext/ { $0 = $0 line }
    1'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .