Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

lines: first end thid, fouth and sixth, and so on... 4

Status
Not open for further replies.

ogniemi

Technical User
Nov 7, 2003
1,041
PL
I have a text file containing:

aline1
aline2
aline3
bline1
bline2
bline3
cline1
cline2
cline3
...
...


I need to process this file to get output like:

aline1 aline3
bline1 bline3
cline1 cline3
...
...

thx in adv.r,m.
 
There is probably a shorter version of this, but I'm still learning sed...

[tt]sed -n 'h;n;n;H;x;s/\n/ /;p;' inputfile[/tt]

Annihilannic.
 
could you please explain in detail "how it works - what means '1~3h;3~3{H;g; and so on" and what is the difference in both methods?

sed -n '1~3h;3~3{H;g;s/\n/ /;p}'

sed -n 'h;n;n;H;x;s/\n/ /;p;'
 
It's all described on the sed man page, but here goes for my version:

[tt]sed -n ' # stream edit, don't print lines by default
h; # copy pattern space (i.e. the line) to hold space
n; # read the next line into pattern space
n; # read the next line into pattern space
H; # append the pattern space to the hold space
x; # swap the hold space and pattern space
s/\n/ /; # replace the carriage return in the pattern
# space with a 'space'
p; # print the patern space
'[/tt]

As you can see sed has two 'spaces' where it can hold data, the pattern space, where every line is read into by default, and the hold space, where you can save stuff for use later in the script.

I'll let feherke describe his version. :)

Annihilannic.
 
Hi

My code is flexible, Annihilannic's code is portable.
Code:
1~3            [gray]# start on line [b]1[/b], repeat for each [b]3[/b]rd[/gray]
    h          [gray]# copy pattern space to [b]h[/b]old space[/gray]
3~3            [gray]# start on line [b]3[/b], repeat for each [b]3[/b]rd[/gray]
    {          [gray]# do the following...[/gray]
      H        [gray]# append patter space to [b]H[/b]old space[/gray]
      g        [gray]# copy hold space to pattern space[/gray]
      s/\n/ /  [gray]# [b]s[/b]ubstitute newline character with space[/gray]
      p        [gray]# [b]p[/b]rint the current pattern space[/gray]
    }          [gray]# ...do until here[/gray]

Feherke.
 
Another way:
awk 'NR%3==1{a=$0}!(NR%3){print a,$0}' /path/to/input > output

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top