Help with AWK

I need to cut the first and last field from a "|" delimited flat file and write the remianing fields onto a new file with the same delimiter. I have to do this to n number of files which always have different set of fields in them. Can anyone help me out.

Thanks

This ought to work:

awk 'BEGIN {FS="|"; OFS="|"} {print $1,$NF}' myfile > newfile

Edit: Wait, you want to place all fields except the first and last in the new file? I think I misread your problem.

awk -F"|" '{ str=$2;for(i=3;i<NF;++i) str=str FS $i; print str }' f1

anbu,

I need each file to write to a new file after removing the first and last fields.

How can i acheive it?

Thanks

Redirect stdout:

awk -F"|" '{ str=$2;for(i=3;i<NF;++i) str=str FS $i; print str }' f1 > newfile

Glenn,

I understood little about this code. Can you put everything in place for me.

I understood that we defined the field seperator as "|" but next

means for str=$2 starting from second field till the end except the last field print everythnig right. But what is str=str. Please explain.

And how should i use this code on a file.

I just copied anbu23's code and added the "> newfile" in red after it to show how to redirect the results into a new file. anbu23 would be able to explain his code better than I would, although I think your question about "str=str" lies in confusion over the syntax. In fact, the full assignment is "str=str FS $i;" (i.e., str is being set equal to everything up to the semicolon) -- in this case, str is set to the value of str followed by the file separator "FS", in this case "|", followed by the value of the current field being processed ($i).

I'm not sure if I understand your question about how to use the code on a file... in anbu23's example, "f1" is the original file.

I'll explain this code with an example, suppose your sample input line is as follows:

ABC|DEF|GHI|JKL|MNO|PQR

You want to omit first and last field from this line and print all other fields with field separator.

str=$2;for(i=3;i<NF;++i) str=str FS $i; print str

Variable str is assigned the value of 2nd field which is DEF, then loop begins, in the first iteration of loop, str is assigned the value, str=str FS $i where str=DEF, FS=| and $i or $3=GHI, so it becomes str=DEF|GHI and then in the 2nd iteration of loop str=DEF|GHI FS=| $4=JKL ie str=DEF|GHI|JKL, in this way loop continues until 2nd last field of the line, yeilding DEF|GHI|JKL|MNO