How to replace entire column without losing formatting in awk

Editor’s Note :
This question has a problematic history of changes in that well-designed but erroneous editing (which introduced unrelated, “pretty” formatting based on spaces and characters |to separate columns) temporarily confused the problem (since it returned) .
The premise of the OP is that the input is separated by tabs, even if it is not directly reflected in the sample presented here.

I have an input file having 6 columns and they are separated by tabs. I want to replace all the values ​​in column 5 with a value '81115'while keeping the formatting intact.

Input file:

203           ADD              24       IAC              81216            IT     
204           ATT              24       IAC              81216            IT  

Desired output file:

203           ADD              24       IAC              81115            IT  
204           ATT              24       IAC              81115            IT  

My solution # 1

:

awk '{$5 = v} 1' v="81115" file > file.NEW

5 , .

:

203 ADD 24 IAC 81115 IT 

204 ATT 24 IAC 81115 IT 

# 2

, :

awk -v replace="81115" -F '\t' -v OFS='\t' {$5=replace}1' file > file.NEW

awk -F"\t" -v OFS="\t" '{$5=81115}1' file > file.NEW

awk -F '\t' '{$5="81115";}1' OFS='\t' file > file.NEW

, 81115; .. 7.

:

203           ADD              24       IAC              81216            IT            81115

204           ATT              24       IAC              81216            IT            81115

- ?

+4
3

, , split. , split GNU awk.

:

 awk '{split($0, a, FS, seps)          # split based on FS
      a[5]="81115";                    # Update the 5th column
      for (i=1;i<=NF;i++)              # print the data back
         printf("%s%s", a[i], seps[i]) # keeping the separators
      print ""}'                       # print a new line

:

 awk '{split($0, a, FS, seps); a[5]="81115"; for (i=1;i<=NF;i++) printf("%s%s", a[i], seps[i]); print ""}' /tmp/data

fooobar.com/questions/1256037/...

+1

:
- GNU awk, . @Sundeep , , , . Jay Rajput: .
- , .

, , OFS, , Awk .
( , $5 = ..., , OFS ( ) , () , .)

, , , .

cat -et, , : ^I cat -et.

/ , awk , , .
, OFS :

awk -v replace='81115' -v OFS='\t' '{$5=replace}1' file

-F, Awk.

, .

0

, , sed, , 5- 81216, 1-4

$ sed 's/81216/81115/' file 
203           ADD              24       IAC              81115            IT     
204           ATT              24       IAC              81115            IT  


- 5- ,

sed -E 's/^((\S+\s+){4})\S+/\181115/' file

\s \s ,

sed -E 's/^(([^[:space:]]+[[:space:]]+){4})[^[:space:]]+/\181115/' file 


GNU awk, gensub

awk '{$0 = gensub(/^((\S+\s+){4})\S+/, "\\181115", "1", $0)}1' file

,

awk -v replace='81115' '{$0 = gensub(/^((\S+\s+){4})\S+/, "\\1"replace, "1", $0)}1' file 


0

Source: https://habr.com/ru/post/1652440/


All Articles