TransWikia.com

How to move string from one line to another

Unix & Linux Asked on November 14, 2021

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

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 ......

Answered by Gilles Quenot on November 14, 2021

$ printf '1m2n,pn' | 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.

Answered by Kusalananda on November 14, 2021

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

Answered by JigglyNaga on November 14, 2021

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

Answered by V.D.D on November 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP