Remove the file content based on the Header of the file

Hi All,

I want to remove the content based on the header information .
Please find the example below.

File1.txt

Name|Last|First|Location|DepId|Depname|DepLoc
naga|rr|tion|hyd|1|wer|opr
Nava|ra|tin|gen|2|wera|opra

I have to search for the DepId and remove the data from the DepId to the end of the file.

output.txt

Name|Last|First|Location|DepId
naga|rr|tion|hyd|1|wer
Nava|ra|tin|gen|2|wera

Thanks in Advance.

 
$ nawk -F\| '{for(i=1;i<=4;i++)printf("%s|",$i);print $5}' input.txt
Name|Last|First|Location|DepId
naga|rr|tion|hyd|1
Nava|ra|tin|gen|2
1 Like

hi itkamaraj, Thanks for the reply.. i hope we can do the above only for the 5th filed.. if i want to search for the particular field and remove the fields from then.. the exact req is where ever the DepId is i have remove the all other coulumns after DepId.. Thanks for undertanding..

try this..

 
awk -F\| 'NR==1{for(i=1;i<=NF;i++)if($i~/DepId/)val=i}{for(i=1;i<=val-1;i++)printf("%s|",$i);print $val}' input.txt
1 Like

With gawk:

gawk -F\| 'NR==1{
for(i=1;i<=NF;i++)
 if($i~from)
 {
  fromn=i
  break
 }
 NF=fromn;print
 next
}{NF=fromn}1' from='DepId' OFS='|' infile

Just replace value of the from variable as per your requirement...

1 Like

@itkamaraj : The code is working as expected.. Thanks once again :slight_smile:

@elixir_sinari : Thanks for replying.. working as expected :slight_smile: :slight_smile:

1 Like