How to subtract rows (lines) with AWKHow to limit printed output based on number of occurences (AWK)How to subtract rows from first row using awk?Subset rows with awkBasic grep/awk help - extracting all lines containing a list of terms from one file into a separate fileHow to subtract dates from colums using awk?How to subtract const from the file in awk?How do I append text from one line, to the end of another?“Level 2 halted” error message using ldattach with mux type GSM0710Remove rows from a file with awkawk from different lines

What is the word for reserving something for yourself before others do?

Languages that we cannot (dis)prove to be Context-Free

How to format long polynomial?

How is it possible to have an ability score that is less than 3?

How is the claim "I am in New York only if I am in America" the same as "If I am in New York, then I am in America?

How to determine what difficulty is right for the game?

Today is the Center

Why doesn't H₄O²⁺ exist?

Replacing matching entries in one column of a file by another column from a different file

Arrow those variables!

Character reincarnated...as a snail

What's the output of a record needle playing an out-of-speed record

Find the result of this dual key cipher

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

Intersection point of 2 lines defined by 2 points each

Was any UN Security Council vote triple-vetoed?

Is it unprofessional to ask if a job posting on GlassDoor is real?

Is there a name for fork-protected pieces?

Is it possible to run Internet Explorer on OS X El Capitan?

Malcev's paper "On a class of homogeneous spaces" in English

Theorems that impeded progress

What does the "remote control" for a QF-4 look like?

Can a Cauchy sequence converge for one metric while not converging for another?

tikz convert color string to hex value



How to subtract rows (lines) with AWK


How to limit printed output based on number of occurences (AWK)How to subtract rows from first row using awk?Subset rows with awkBasic grep/awk help - extracting all lines containing a list of terms from one file into a separate fileHow to subtract dates from colums using awk?How to subtract const from the file in awk?How do I append text from one line, to the end of another?“Level 2 halted” error message using ldattach with mux type GSM0710Remove rows from a file with awkawk from different lines






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















I'm trying to figure out how I can use AWK to subtract lines. For example, imagine the input file is:



30
20


The output would be:



10


Now, as a test I am trying to calculate the "Used" memory column from:



$ cat /proc/meminfo


So at the moment I have written this:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
-- Here comes the calculation using AWK


I have tried the following:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk '$0-ss=$0 END print s'


But this just gives me the last row of data.



I've found a working solution, but I doubt it's the most optimal one. All my coding experience tells me that hard coding the amount of rows is terrible :P



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk 'NR == 1s=$0 NR == 2 s=s-$0 END print s'









share|improve this question
























  • What would you want done with N rows? Should the final result be line1_$2 - line2_$2 - lineN-$2? Do you only want to subtract the first two consecutive rows?

    – terdon
    Mar 2 '14 at 16:55


















8















I'm trying to figure out how I can use AWK to subtract lines. For example, imagine the input file is:



30
20


The output would be:



10


Now, as a test I am trying to calculate the "Used" memory column from:



$ cat /proc/meminfo


So at the moment I have written this:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
-- Here comes the calculation using AWK


I have tried the following:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk '$0-ss=$0 END print s'


But this just gives me the last row of data.



I've found a working solution, but I doubt it's the most optimal one. All my coding experience tells me that hard coding the amount of rows is terrible :P



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk 'NR == 1s=$0 NR == 2 s=s-$0 END print s'









share|improve this question
























  • What would you want done with N rows? Should the final result be line1_$2 - line2_$2 - lineN-$2? Do you only want to subtract the first two consecutive rows?

    – terdon
    Mar 2 '14 at 16:55














8












8








8


1






I'm trying to figure out how I can use AWK to subtract lines. For example, imagine the input file is:



30
20


The output would be:



10


Now, as a test I am trying to calculate the "Used" memory column from:



$ cat /proc/meminfo


So at the moment I have written this:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
-- Here comes the calculation using AWK


I have tried the following:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk '$0-ss=$0 END print s'


But this just gives me the last row of data.



I've found a working solution, but I doubt it's the most optimal one. All my coding experience tells me that hard coding the amount of rows is terrible :P



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk 'NR == 1s=$0 NR == 2 s=s-$0 END print s'









share|improve this question
















I'm trying to figure out how I can use AWK to subtract lines. For example, imagine the input file is:



30
20


The output would be:



10


Now, as a test I am trying to calculate the "Used" memory column from:



$ cat /proc/meminfo


So at the moment I have written this:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
-- Here comes the calculation using AWK


I have tried the following:



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk '$0-ss=$0 END print s'


But this just gives me the last row of data.



I've found a working solution, but I doubt it's the most optimal one. All my coding experience tells me that hard coding the amount of rows is terrible :P



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | awk 'NR == 1s=$0 NR == 2 s=s-$0 END print s'






linux awk






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 2 '14 at 21:40









Peter Mortensen

91259




91259










asked Mar 2 '14 at 16:32









Dylan MeeusDylan Meeus

3012410




3012410












  • What would you want done with N rows? Should the final result be line1_$2 - line2_$2 - lineN-$2? Do you only want to subtract the first two consecutive rows?

    – terdon
    Mar 2 '14 at 16:55


















  • What would you want done with N rows? Should the final result be line1_$2 - line2_$2 - lineN-$2? Do you only want to subtract the first two consecutive rows?

    – terdon
    Mar 2 '14 at 16:55

















What would you want done with N rows? Should the final result be line1_$2 - line2_$2 - lineN-$2? Do you only want to subtract the first two consecutive rows?

– terdon
Mar 2 '14 at 16:55






What would you want done with N rows? Should the final result be line1_$2 - line2_$2 - lineN-$2? Do you only want to subtract the first two consecutive rows?

– terdon
Mar 2 '14 at 16:55











3 Answers
3






active

oldest

votes


















9














You can also do this using awk, paste, and bc. I find this approach easier to remember, the syntax of awk always requires me to look things up to confirm.



NOTE: This approach has the advantage of being able to contend with multiple lines of output, subtracting the 2nd, 3rd, 4th, etc. numbers from the 1st.



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2' | paste -sd- - | bc
7513404


Details



The above uses awk to select the column that contains the numbers we want to subtract.



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2'
7969084
408432


We then use paste to combine these 2 values values and add the minus sign in between them.



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2'| paste -sd- -
7969084-346660


When we pass this to bc it performs the calculation.



$ grep -P 'MemTotal|MemFree' /proc/meminfo | 
awk 'print $2'| paste -sd- - | bc
7513404





share|improve this answer

























  • @terdon - thanks I was making that edit when you did it 8-)

    – slm
    Mar 2 '14 at 17:00


















3














The purely awk solution, no redundant cat or grep commands:



awk '/MemTotal/ TOT=$2 /MemFree/ FREE=$2 END printf("%d kB Usedn", TOT-FREE)' /proc/meminfo



I see awk_FTW beat me to it but I though formatting the output could be nice.






share|improve this answer






























    3














    Try this:



    grep -P 'MemTotal|MemFree' /proc/meminfo | 
    awk 'NR==1s=$2;nexts-=$2ENDprint s'





    share|improve this answer

























      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "106"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f117785%2fhow-to-subtract-rows-lines-with-awk%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      9














      You can also do this using awk, paste, and bc. I find this approach easier to remember, the syntax of awk always requires me to look things up to confirm.



      NOTE: This approach has the advantage of being able to contend with multiple lines of output, subtracting the 2nd, 3rd, 4th, etc. numbers from the 1st.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2' | paste -sd- - | bc
      7513404


      Details



      The above uses awk to select the column that contains the numbers we want to subtract.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'
      7969084
      408432


      We then use paste to combine these 2 values values and add the minus sign in between them.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- -
      7969084-346660


      When we pass this to bc it performs the calculation.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- - | bc
      7513404





      share|improve this answer

























      • @terdon - thanks I was making that edit when you did it 8-)

        – slm
        Mar 2 '14 at 17:00















      9














      You can also do this using awk, paste, and bc. I find this approach easier to remember, the syntax of awk always requires me to look things up to confirm.



      NOTE: This approach has the advantage of being able to contend with multiple lines of output, subtracting the 2nd, 3rd, 4th, etc. numbers from the 1st.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2' | paste -sd- - | bc
      7513404


      Details



      The above uses awk to select the column that contains the numbers we want to subtract.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'
      7969084
      408432


      We then use paste to combine these 2 values values and add the minus sign in between them.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- -
      7969084-346660


      When we pass this to bc it performs the calculation.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- - | bc
      7513404





      share|improve this answer

























      • @terdon - thanks I was making that edit when you did it 8-)

        – slm
        Mar 2 '14 at 17:00













      9












      9








      9







      You can also do this using awk, paste, and bc. I find this approach easier to remember, the syntax of awk always requires me to look things up to confirm.



      NOTE: This approach has the advantage of being able to contend with multiple lines of output, subtracting the 2nd, 3rd, 4th, etc. numbers from the 1st.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2' | paste -sd- - | bc
      7513404


      Details



      The above uses awk to select the column that contains the numbers we want to subtract.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'
      7969084
      408432


      We then use paste to combine these 2 values values and add the minus sign in between them.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- -
      7969084-346660


      When we pass this to bc it performs the calculation.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- - | bc
      7513404





      share|improve this answer















      You can also do this using awk, paste, and bc. I find this approach easier to remember, the syntax of awk always requires me to look things up to confirm.



      NOTE: This approach has the advantage of being able to contend with multiple lines of output, subtracting the 2nd, 3rd, 4th, etc. numbers from the 1st.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2' | paste -sd- - | bc
      7513404


      Details



      The above uses awk to select the column that contains the numbers we want to subtract.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'
      7969084
      408432


      We then use paste to combine these 2 values values and add the minus sign in between them.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- -
      7969084-346660


      When we pass this to bc it performs the calculation.



      $ grep -P 'MemTotal|MemFree' /proc/meminfo | 
      awk 'print $2'| paste -sd- - | bc
      7513404






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 2 '14 at 17:00

























      answered Mar 2 '14 at 16:55









      slmslm

      255k71541687




      255k71541687












      • @terdon - thanks I was making that edit when you did it 8-)

        – slm
        Mar 2 '14 at 17:00

















      • @terdon - thanks I was making that edit when you did it 8-)

        – slm
        Mar 2 '14 at 17:00
















      @terdon - thanks I was making that edit when you did it 8-)

      – slm
      Mar 2 '14 at 17:00





      @terdon - thanks I was making that edit when you did it 8-)

      – slm
      Mar 2 '14 at 17:00













      3














      The purely awk solution, no redundant cat or grep commands:



      awk '/MemTotal/ TOT=$2 /MemFree/ FREE=$2 END printf("%d kB Usedn", TOT-FREE)' /proc/meminfo



      I see awk_FTW beat me to it but I though formatting the output could be nice.






      share|improve this answer



























        3














        The purely awk solution, no redundant cat or grep commands:



        awk '/MemTotal/ TOT=$2 /MemFree/ FREE=$2 END printf("%d kB Usedn", TOT-FREE)' /proc/meminfo



        I see awk_FTW beat me to it but I though formatting the output could be nice.






        share|improve this answer

























          3












          3








          3







          The purely awk solution, no redundant cat or grep commands:



          awk '/MemTotal/ TOT=$2 /MemFree/ FREE=$2 END printf("%d kB Usedn", TOT-FREE)' /proc/meminfo



          I see awk_FTW beat me to it but I though formatting the output could be nice.






          share|improve this answer













          The purely awk solution, no redundant cat or grep commands:



          awk '/MemTotal/ TOT=$2 /MemFree/ FREE=$2 END printf("%d kB Usedn", TOT-FREE)' /proc/meminfo



          I see awk_FTW beat me to it but I though formatting the output could be nice.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Apr 15 '14 at 12:51









          JohanJohan

          2,80721829




          2,80721829





















              3














              Try this:



              grep -P 'MemTotal|MemFree' /proc/meminfo | 
              awk 'NR==1s=$2;nexts-=$2ENDprint s'





              share|improve this answer





























                3














                Try this:



                grep -P 'MemTotal|MemFree' /proc/meminfo | 
                awk 'NR==1s=$2;nexts-=$2ENDprint s'





                share|improve this answer



























                  3












                  3








                  3







                  Try this:



                  grep -P 'MemTotal|MemFree' /proc/meminfo | 
                  awk 'NR==1s=$2;nexts-=$2ENDprint s'





                  share|improve this answer















                  Try this:



                  grep -P 'MemTotal|MemFree' /proc/meminfo | 
                  awk 'NR==1s=$2;nexts-=$2ENDprint s'






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Apr 19 '14 at 16:56









                  slm

                  255k71541687




                  255k71541687










                  answered Mar 2 '14 at 16:36









                  cuonglmcuonglm

                  106k25210308




                  106k25210308



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f117785%2fhow-to-subtract-rows-lines-with-awk%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

                      Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

                      NetworkManager fails with “Could not find source connection”Trouble connecting to VPN using network-manager, while command line worksHow can I be notified about state changes to a VPN adapterBacktrack 5 R3 - Refuses to connect to VPNFeed all traffic through OpenVPN for a specific network namespace onlyRun daemon on startup in Debian once openvpn connection establishedpfsense tcp connection between openvpn and lan is brokenInternet connection problem with web browsers onlyWhy does NetworkManager explicitly support tun/tap devices?Browser issues with VPNTwo IP addresses assigned to the same network card - OpenVPN issues?Cannot connect to WiFi with nmcli, although secrets are provided