Saturday 26 May 2018

macos - How to extract two numbers from two strings and calculate the difference in Bash?


I have a text file which contains (among others) the following lines:


{chapter}{{1}Einleitung}{27}{chapter.1}  
{chapter}{{2}Grundlagen}{35}{chapter.2}

How can I



  • get the 2 lines from this text file (they will always contain }Einleitung resp. }Grundlagen} and

  • extract the 2 page numbers (in this case 27 and 35),

  • calculate the difference 35-27 = 8 and

  • save the difference (8) of the two numbers in a variable


Perhaps with a bash script in Mac OS X?



Answer



I do not know if Mac OS X has awk. If it does, this should work:


This should work:


DIFFERENZ=$(awk 'BEGIN {
FS="[{}]+"
} {
if ($4=="Einleitung")
EINLEITUNG=$5
if ($4=="Grundlagen")
GRUNDLAGEN=$5
} END {
print GRUNDLAGEN-EINLEITUNG
}' textfile)

How it works:



  • FS="[{}]+" sets the field separator to any combination of curly brackets.

  • $4 refers to the third filed on the line (separated by curly brackets).

  • DIFFERENZ=$(...) evaluates the command ... and stores the ouput in DIFFERENZ.


No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...