3

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.

4 Answers 4

3
sed -e '1~2{h;d};G'

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
3
  • The output is only 2 lines long Commented Jul 21, 2020 at 22:22
  • @GillesQuenot Edited; the question previously had extra blank lines that needed deleting. My updated answer now works for the output of eg. seq 1 4.
    – JigglyNaga
    Commented Jul 23, 2020 at 13:14
  • ???? Not my response, mine is Perl Commented Jul 23, 2020 at 13:57
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.

0

Using , if your file is not too big to be slurped in RAM memory:

perl -0 -e '                     # -0 slurp the whole file 
    $\ = $, = "\n";              # change record & list separator
    my @file = split /\n/, <>;   # split the file on line per array value
    print @file[1,0,2..$#file]   # array slice
' file

If you want to replace in place, use

perl -i -e ......

You must log in to answer this question.

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