Wednesday, May 15, 2024
3
rated 0 times [  3] [ 0]  / answers: 1 / hits: 1092  / 1 Year ago, fri, may 26, 2023, 6:17:38

I want to get the integer value after a specific string from a file and sort all the integers.
Ex -
I have a file with thousands of lines with string weight,



-weight 100
-weight 200
-weight 20


I want to get all the integer values in sorted order.


More From » command-line

 Answers
2

If you are searching for the longest string of numbers that is the last thing on the line, you can just use grep:



$ grep -oP 'd+s*$' file 
100
200
20


The -o tells grep to only print the matching portion of the line and the -P enables Perl Compatible Regular Expressions. PCREs let us use d+ for "one or more digits" and s* for "0 or more whitespace characters". So, all together, that command will print the longest stretch of numbers found at the end of the line.



If you need them sorted, just pass through sort:



$ grep -oP 'd+s*$' file | sort -n
20
100
200


If, instead, you need to anchor your pattern using a specific string, use:



$ grep -oP -- '-weights+Kd+' file | sort -n
20
100
200


The K tells grep not to include anything matched up to this point, so the command above will only print the longest stretch of numbers after the -weight and 0 or more spaces.



Note that if you want to also include negative numbers or decimals, you will need:



grep -oP -- '-weights+K[0-9,-]+' file | sort -n


For example:



$ cat file 
-weight 100
-weight 200
-weight 20
-weight -29
-weight -32.4

$ grep -oP -- '-weights+K[0-9,-]+' file | sort -n
-32
-29
20
100
200

[#5444] Sunday, May 28, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
itteast

Total Points: 291
Total Questions: 123
Total Answers: 104

Location: Tuvalu
Member since Wed, Mar 29, 2023
1 Year ago
;