Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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'
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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