1

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.

4
  • 1
    Please state clearly your input and expected output. It will be easy to help you out that way! Commented Apr 5, 2017 at 16:36
  • Added the result, hope it will help. Commented Apr 5, 2017 at 16:59
  • 2 # if idOpen was 2 for 2 times - shouldn't be 3(as it already has 2 in the second row) ? Commented Apr 5, 2017 at 17:38
  • @RomanPerekhrest thar was my mistake, in the beginning it has a value 0, every time when this script will be started and i will chose number as an IdOpen, value must increase by 1, it is just a counter of opens. Commented Apr 5, 2017 at 18:05

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.