Abhinay
Abhinay

Reputation: 75

Updating counter in a file from shell script

I have a txt file which has the stats of file transfered to diff remote machines as mentioned below

172.31.32.5 yes 2
172.31.32.6 yes 3

Now when 3 more files are transferred to first machine i want the file to be updated to below from a shell script

172.31.32.5 yes 5
172.31.32.6 yes 3

I was planning to use some thing like this

sed -i '/$IP/d' /tmp/fileTrnsfr
echo "$IP yes $((oldcount + newcount))

But looking for a better solution which would search, update and replace using sed or awk commands

Upvotes: 1

Views: 837

Answers (3)

Adam Katz
Adam Katz

Reputation: 16118

Entirely native in portable POSIX shell:

#!/bin/sh

# read data from arguments (or else standard input), line by line
cat "${@:-/dev/stdin}" |while read line; do
  number="${line##*[^0-9]}"  # extract the number at the end of the line
  line="${line%$number}"     # remove that number from the end of the line
  echo "$line$((number+3))"  # append (number+3) to the end of the line
done

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246744

This requires GNU sed:

$ cat fileTrnsfr 
172.31.32.5 yes 2
172.31.32.6 yes 3

$ newcount=3
$ ip=172.31.32.5

$ sed -i -r '
    /^'"${ip//./\\.}"'/ {
        s/(.*) ([[:digit:]]+)/printf "%s %d" "\1" "$(expr \2 + '"$newcount"')"/
        e
    }
' fileTrnsfr 

$ cat fileTrnsfr 
172.31.32.5 yes 5
172.31.32.6 yes 3

That transforms the line

172.31.32.5 yes 2

into

printf "%s %d" "172.31.32.5 yes" "$(expr 2 + 3)"

and then uses the e command to execute it as a command (using /bin/sh, I believe)

Upvotes: 0

Inian
Inian

Reputation: 85550

You can use Awk to achieve this. You need to import the variables containing the IP information and number of files to the context fo Awk and modify it.

temp_file="$(mktemp)"
awk -v ip="$ip" -v count="$newcount" '$1==ip{$NF+=count}1' /tmp/fileTrnsfr > "$temp_file" && mv "$temp_file" /tmp/fileTrnsfr

The mktemp is for creating a temporary name used to write the contents of Awk and move it back the original file name (simulation for the in-place file edit)

The above is for older non GNU variants of Awk which do not support in-place edit.

In latest GNU Awk (since 4.1.0 released), it has the option of "inplace" file editing:

[...] The "inplace" extension, built using the new facility, can be used to simulate the GNU "sed -i" feature. [...]

gawk -i inplace -v INPLACE_SUFFIX=.bak -v ip="$ip" -v count="$newcount" '$1==ip{$NF+=count}1' /tmp/fileTrnsfr 

Upvotes: 2

Related Questions