LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   Conditional editing of a file through Shell script (https://www.linuxquestions.org/questions/linux-general-1/conditional-editing-of-a-file-through-shell-script-925212/)

Linuxahoy 01-23-2012 03:40 AM

Conditional editing of a file through Shell script
 
Hi,

I am trying to write a small shell script. The purpose of the script is...
I have a tabulated data in a file as follows.
Serial No USN field1 field2 field3 field4 Name
1 794 1.83 1.83 0.00 3.67 con
2 686 0.00 0.00 0.00 0.00 abc
3 883 0.00 0.00 0.00 0.00 xyz
4 872 0.92 0.00 0.00 0.92 lmn
5 705 0.00 0.00 0.00 0.00 cat
6 628 0.92 4.59 0.00 5.50 etc
7 958 0.00 0.00 0.00 0.00 lop
8 957 0.00 0.00 0.00 0.00 nam
9 956 0.00 0.00 0.00 0.00 mak
10 955 0.00 0.00 0.00 0.00 lab

the size of the file will be several hundred lines. The script should read the file and if a particular value is found in the "USN" column(Value will be provided through a variable), then the content of last column "Name" should be changed.
i.e if $usn is the variable containing the search value, I want to find if $usn is present in the "USN" column. If yes, I want to replace the last column of that line with a value present in another variable $name.
Ex:
$usn=628
$name=ham
since 628 is present in 6th line, the "Name" column data of that line should be replaced with ham.

Please let me know how I can achieve this. I am not able to figure out if awk can be used here.
Please help.

H_TeXMeX_H 01-23-2012 04:33 AM

You should be able to do this using awk:
http://www.grymoire.com/Unix/Awk.html

You can pass the variable in and then use awk to test one column and change another column.

druuna 01-23-2012 04:45 AM

Hi,

A working solution:
Code:

#!/bin/bash

if [[ $# != 2 ]]
then
  echo "Please provide correct input..."
  exit 1
fi

usn=$1
newName=$2

awk -v usn="$usn" -v newName="$newName" '
  { if ( $2 == usn ) { $7 = newName } }
  { print $0 }
' infile

It is up to you to figure out how this works :)

Hope this helps.


All times are GMT -5. The time now is 06:21 AM.