How to Print from nth field to mth fields using awk

Hi,

Is there any short method to print from a particular field till another filed using awk?

Example File:

File1
====
1|2|acv|vbc|......|100|342
2|3|afg|nhj|.......|100|346

Expected output:

File2
====
acv|vbc|.....|100
afg|nhj|.....|100

In the above example, let say I have 101 fields, I have print line only from 3 field to 100 field.

Is

awk '{print $3FS$4FS$5FS....$100}'

is the only method or is it possible to just mention the starting field and the ending field and get the line printed?

Try like...

cut -d'|' -f 2-9 test.txt

Try:

awk -F\| '{sub($1"\\|"$2"\\|",x)}1' infile

bmk,
Thanks. But I was luking for some awk solution :slight_smile:

Scruntizer,
Could yoy please give a explanation of the code? I tried it but it wasn't wokring in the way I was hoping for.

I test like:

106089|machomaddy|ZHealth|Y
106089|machomaddy|ZNetworks|N
106089|machomaddy|ZNetworks|N

Expected output:

machomaddy|ZHealth|Y
machomaddy|ZNetworks|N
machomaddy|ZNetworks|N

But the code was producing

ZHealth|Y
ZNetworks|N
ZNetworks|N

Try like..

awk -F'|' -v f=2 -v t=4 '{ for (i=f; i<=t;i++) printf("%s%s", $i,(i==t) ? "\n" : OFS) }' test.txt
1 Like

Well my suggestion was for cutting the first two fields, as per your example. Only the first column:

awk -F\| '{sub($1"\\|",x)}1' infile

an additional try @Scrutinizer's solution

# awk '{sub("^[^|]*\\|","")}1' infile
machomaddy|ZHealth|Y
machomaddy|ZNetworks|N
machomaddy|ZNetworks|N
awk -F"\|"  '{sub(".*"$1 FS,x);NF--}1' OFS="|" yourfile

this will also work if you want to cut from $2 instead of $1 :

awk -F"\|"  '{sub(".*"$2 FS,x);NF--}1' OFS="|" yourfile

---------- Post updated at 02:51 PM ---------- Previous update was at 02:47 PM ----------

$ cat f1
106089|machomaddy|ZHealth|Y
106089|machomaddy|ZNetworks|N
106089|machomaddy|ZNetworks|N
$ awk -F"\|"  '{sub(".*"$1 FS,x);NF--}1' OFS="|" f1
machomaddy|ZHealth
machomaddy|ZNetworks
machomaddy|ZNetworks
$ awk -F"\|"  '{sub(".*"$2 FS,x);NF--}1' OFS="|" f1
ZHealth
ZNetworks
ZNetworks

Another awk solution:

~/unix.com$ awk '{OFS=""; S=""; i=start-1; while(i++<end){S=S OFS $i;OFS=FS}}$0=S' start=3 end=99 FS='|' file

Set start and end at the end of the line to match your requirements

1 Like