awk - one liners

Guys,

I have a requirement like this.

A file has >5K records always. Separated by "|", it has 30 fields for each line. In some lines, I am getting an odd field. say, the 15th field is supposed to be 2 characters but comes in as >2. In this case, for resolving this I need to copy the value of 25th field to the 15th. See below.

||||||||||||||Praveen||||||||||PK||||||

Output needed

||||||||||||||PK||||||||||PK||||||

Lines tried:

awk FS="|" OFS="|" '{if(length($15)>2) $15=$25; print $0;}' file

Never succeeded! Please advise. :slight_smile:

 
$ cat input.txt
||||||||||||||Praveen||||||||||PK||||||
||||||||||||||Praveen||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
||||||||||||||Praveen||||||||||PK||||||
||||||||||||||Praveen||||||||||PK||||||
 
$ nawk -F\| -v OFS=\| 'length($15)>2{$15=$25}1' input.txt
||||||||||||||PK||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
||||||||||||||PK||||||||||PK||||||
 

your logic also work. explain the issue (what output you are getting with your awk? )

$ cat file
||||||||||||||Praveen||||||||||PK||||||

$ awk 'BEGIN{FS=OFS="|"} length($15)>2{$15=$25}1' file
||||||||||||||PK||||||||||PK||||||

@Pikk45 - Just small change to your code.. also works:)

 awk -F\| '{if(length($15)>2) $15=$25; print $0;}' OFS="|"  file

or

awk '{if(length($15)>2) $15=$25; print $0;}' FS="|" OFS="|"  file

awk 'length($15)>2{$15=$25}1' FS=\| OFS=\| file

Thanks alot!

itkamaraj: nawk is not supported :frowning: :frowning:

pamu: Thanks man. You got me on this one!!! :smiley:

Jotne: Thanks a bunch :slight_smile: :slight_smile: I should have learnt about adding FS n OFS to the end :wink:

try awk instead of nawk.

awk '{sub(/...+/,$25,$15)}1' FS=\| OFS=\| file