Skip to main content

Replace column value of text files using awk



AWK is a handy tool to process large text files.

Ever came across a need to replace 100 or more text files value in a single column?

Of course, the old school method is to do it manually which is definitely time consuming and not efficient at all.

Below is a sample code how to replace value in a column for all text files found in the directory specified.

#!/bin/bash

for file in /home/pc_text/Documents/source/*

do
xfilename=$(basename $file)

#echo "$xfilename" if you need to display the filename while the code is running

awk 'FNR==1{print $0}' $file >> /home/pc_text/Documents/output/$xfilename

awk 'NR>1{print $1 , $2 , $3 , $4  , "0.873" , $6 , $7 }' $file >> /home/pc_text/Documents/output/$xfilename

done

Code explanation:

for file in /home/pc_text/Documents/source/* - get all text files for processing

xfilename=$(basename $file) – get all the filename of the text files

awk 'FNR==1{print $0}' $file >> /home/pc_text/Documents/output/$xfilename – print the first line of the text file or the header so the values remain the same

awk 'NR>1{print $1 , $2 , $3 , $4  , "0.873" , $6 , $7 }' $file >> /home/pc_text/Documents/output/$xfilename – replace the value of the 5th column with 0.873 and create a text file on the output directory


Cheers!! Till next time. Happy Coding!!!

================================
Free Android Apps:

Click  links below to find out more:

Excel Keyboard guide:


Heaven's Dew Fall  Prayer app for Android :



Catholic Rosary Guide  for Android:


Divine Mercy Chaplet Guide (A Powerful prayer):


Comments