awk: print sum of array values and remaining record
Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
Details:
The input file has a constant number of fields (NR=4).
Using awk, I am trying to place (as the second field of the output) the sum of the figure(s) between brackets in field 2 of the input.
So far, I have only been able to simplify the second field of the input and print the entire corresponding record using this code,
You want to extract the numbers from the $2 field of your input. A regular expression to match numbers is '[:digit:]+'. This can be used in the patsplit function.
Code:
awk -F"|" '{t=0; n=patsplit($2,a,/[[:digit:]]+/); for (i in a) t+=a[i]; print n,t}' input
If you don't speak awk fluently, you could use Python.
Code:
#!/usr/bin/env python3
toInsert = 0
outFile = open("beca_new.txt", "w")
# Open the file
with open("beca.txt") as inFile:
for line in inFile: # Read line by line
listLine = line.split('|') # Split into list using | as delim
for char in listLine[1]: # Add up the digits in index 1
if char.isdigit():
toInsert += int(char)
listLine.insert(1, toInsert) # Insert into our list at index 1
toInsert = 0
listLine[1] = str(listLine[1])
print("|".join(listLine), end="") # Print or...
outFile.write("|".join(listLine)) # write to file
outFile.close()
exit(0)
Yes, a lot more characters, I know. But it gets the job done:
I hope this doesn't add to the incomprehensibolity, but you could replicate the patsplit with "split" using the regex allend posted earlier and use the sep array to sum.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.