2

I have been editing a large text file containing pairs of lines as follows (repeated):

\> destination_file.txt

js -e "var e='.jpg',t='b',i='14712583',h='0.us.is.example.com',s='/',n='WIV',u='jasper1123/‌​3/example.com_'+i+n.charAt(2)+n.charAt(0)+n.charAt(1); console.log('http://'+t+h+s+u.charAt(0)+s+u+e);"

CORRECTED VERSION BELOW:

line 1

line 2

line 3

line 4

How can I move the first line to the end of the second line as follows:

line 2

line 1

line 4

line 3

The text file contains thousands of pairs of lines as above.

Is there a terminal command I can run to do this?

Basically, the data above is the result of combining and editing numerous html pages.

Any suggestions would be appreciated.

I have gotten this far in large part from the help here on this forum.

3

Assuming the blank line in your example was for illustrative purposes only:

sed -e '1~2{h;d};G;s/\n//'

That GNU sed expression in detail:

1~2 {  # lines 1,3,5,7 etc.
  h      # save line in the hold space
  d      # delete (don't print yet) and start next line
}
# only reached on lines 2,4,6,8 etc.
G        # retrieve from hold space, append to current line
s/\n//   # delete the joining newline
0

I assume the backslash before the > is just a typo. You can use this bash script if your text file is well formed:

#!/bin/bash

while
    read -r a &&  # store one line to $a
    read -r   &&  # consume the blank line
    read -r b     # store another line to $b
do
    echo $b$a     # join those two lines
    read -r       # whatever, try to consume a blank line
done

Save it to s.sh.

You file content is like this:

A

A-

B

B-

C

C-

then run bash s.sh < file.txt you will get:

A-A
B-B
C-C
0
$ printf '1m2\n,p\n' | ed -s file
line 2
line 1
line 3
line 4

The m command moves a line in the ed editor. 1m2 moves line 1 to line 2. ,p displays the modified buffer on standard output.

For an alternative approach which edits the file in-place:

ed -s file <<END_ED
1m2
w
q
END_ED

This performs the move, writes the result back to the file and quits.

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.