0

Im typing to write a script which can read file_name, delimiter and field_number. After that for each row take an input, replace the field (specified by field_number) and output to same file.

For example if the input is as follows:

Ritesh;M;1992
Shakya;F;1993

For the command

bash_script.sh test.csv ";" 3

Iterating through each row if I input 1994 for first and 1995 for second. I want the output to be the as follows caved in the same file.

Ritesh;M;1994
Shakya;F;1995

So far i managed to get upto this point:

#!/usr/bin/env bash
echo "Following is the input needed:";
echo "\$1: FILE_NAME";
echo "\$2: DELIMITER";
echo "\$3: FIELD IN NUMERIC VALUE";

gawk -i inplace -F "$2" '{...}' $1;

Also my version of gawk doesn't support -i. Thanks in advance.

  • What do you mean by "input from reader"? How will the script be run? How will you be giving the replacement patterns? Please edit your question and clarify. – terdon Feb 29 '16 at 10:04
  • AFAIK, GU awk doesn't support in-place editing of files, nor does any other version of awk. -i tells GNU awk to include a file (or as man awk says, Load an awk source library). It doesn't matter - every tool that does support in-place editing (like perl or sed), just does it via writing to a tmp file and mv-ing it into place afterwards or some similar method anyway. you can do the same. – cas Feb 29 '16 at 10:15
  • @cas recent versions of GNU awk (and maybe others) can take -i inplace which makes them act like sed -i. See gnu.org/software/gawk/manual/html_node/… – terdon Feb 29 '16 at 10:22
  • ok, that must be very recent because it's not in debian sid yet - I have gawk 1:4.1.3+dfsg-0.1 installed and there's no mention of -i inplace in the man page. Hmmmm....unless inplace is an awk library, loaded by -i.......oh, it is. /usr/share/awk/inplace.awk. neat. it's mentioned in the info docs, but not in the man page. – cas Feb 29 '16 at 10:25
0

After help from @ClaudioM I found the answer I was looking for.

#!/bin/bash
if [ -z "${3}" ];then
        echo "Usage: <filename> <delimiter> <field_no>"
else
        FILENAME=$1
        DELIMITER=$2
        FIELD_NO=$3
        TEMP_FILE=/tmp/tempFile
        if [ -f $TEMP_FILE ]; then
            rm $TEMP_FILE
        fi
        OLDIFS=$IFS; IFS=$'\n'
        for line in $(cat $FILENAME)
        do
                echo $line
                oldValue=`echo $line|cut -d$DELIMITER -f$FIELD_NO`
                echo "Enter the value to replace [$oldValue]"
                read newValue
                echo $line | awk -F "$DELIMITER" '{$'$FIELD_NO'="'$newValue'"}{print}' OFS=$DELIMITER >> $TEMP_FILE;IFS=$OLDIFS
        done
fi
mv $TEMP_FILE $FILENAME

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.