Vadim Tor
Vadim Tor

Reputation: 40

Replace string in Nth array

I have a .txt file with strings in arrays which looks like these:

    id | String1 | String2 | Counts
    1  | Abc | Abb | 0
    2  | Cde | Cdf | 0

And i want to add counts, so i need to replace last digit, but i need to change it only for the one line.

I am getting new needed value by this function:

$(awk -F "|" -v i=$idOpen 'FNR == i { gsub (" ", "", $0); print $4}' filename)"

And them I want to replace it with new value, which will be bigger for 1. And im doing it right in there.

counts=(("$(awk -F "|" -v i=$idOpen 'FNR == i { gsub (" ", "", $0); print $4}' filename)"+1)) 

Where IdOpen is an id of the array, where i need to replace string.

So i have tried to replace the whole array by these:

counter="$(awk -v i=$idOpen  'BEGIN{FNqR == i}{$7+=1} END{ print $0}' bookmarks)"
N=$idOpen
sed -i "{N}s/.*/${counter}" bookmarks

But it doesn't work!

So is there a way to replace only last string with value which i have got earlier?

As result i need to get:

id | String1 | String2 | Counts
1  | Abc | Abb | 1 # if idOpen was 1 for 1 time 
2  | Cde | Cdf | 2 # if idOpen was 2 for 2 times

And the last number will be increased by 1 everytime when i will activate these commands.

Upvotes: 1

Views: 103

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

awk solution:

setting idOpen variable(for ex. 2):

 idOpen=2

awk -F'|' -v i=$idOpen 'NR>1{if($1 == i) $4=" "$4+1}1' OFS='|' file > tmp && mv tmp file

The output(after executing the above command twice):

cat file

id | String1 | String2 | Counts
1  | Abc | Abb | 0
2  | Cde | Cdf | 2

NR>1 - skipping the header line

Upvotes: 1

Related Questions