Sponsored Content
Top Forums Programming Find and print number after string in C Post 302525445 by cgol on Thursday 26th of May 2011 05:05:06 PM
Old 05-26-2011
Find and print number after string in C

I'm trying find and print a number after a specific user passed string in each line of a text file using C (as requested by the powers that be). I've pieced together enough to read the file, find the string and print the line it was found on but I’m not sure where to even start in terms of finding the number after the string. Any tips would be much appreciated.

The below code outputs the line number where the string is found:
Code:
/* usage exename textfile searchstring */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) 
{ 
FILE *file; 
char line[BUFSIZ]; 
int linen = 1; 
file = fopen(argv[1], "r"); 
if(file != NULL) { 
  while(fgets(line, sizeof(line), file)){ 
     if(strstr(line, argv[2]) != NULL) { 
        printf("Found %s %s %i\n",argv[2],"@ line",linen); 
     }
 ++linen;     
 } 
} 
else { 
  perror(argv[1]); 
  perror(argv[2]); 
} 
fclose(file); 
return 0; 
}

My text file looks like below. I'm trying to print the number as is the file (2 decimals) after "val=".
Code:
123 test=123 val=233.33 x=111 y=222
123 test=123 val=.33 x=111 
123 xr=3 test=123 x=111 y=222
123 test=123 val=233. x=111 y=222
123 test=123 val=233.33 x=111 y=222
 
Output from current code:
Found val @ line 1
Found val @ line 2
Found val @ line 4
Found val @ line 5


Last edited by pludi; 05-27-2011 at 06:53 AM..
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

way to print all the string till we get a space and a number

Is there any way to print all the string till we get a space and a number and store it a variable for eg we have string java.io.IOException: An existing connection was forcibly closed by the remote host 12 All I want is to store "java.io.IOException: An existing connection was forcibly closed... (13 Replies)
Discussion started by: villain41
13 Replies

2. Shell Programming and Scripting

How to print the number of lines from a file, the starting string should be passed`

Hi , I have file, which has the below content: line 100 a b c d line300 a s d f s line200 a s d a (3 Replies)
Discussion started by: little_wonder
3 Replies

3. Shell Programming and Scripting

Find longest string and print it

Hello all, I need to find the longest string in a select field and print that field. I have tried a few different methods and I always end up one step from where I need to be. Methods thus far: nawk '{if (length($1) > long) long=length($1); if(length($1)==long) print $1}' The above... (6 Replies)
Discussion started by: SEinT
6 Replies

4. UNIX for Dummies Questions & Answers

find string and and print another string

i have a file that looks like this ABC123 aaaaaaaaaaaaaaasssssssssssssssffhhh ABC234 EMPTY ABC652 jhfffffffffffffffffffffffffffffffffffkkkkkkkkkkkk i want to grep "EMPTY" and print ABC234 (3 Replies)
Discussion started by: engr.jay
3 Replies

5. Shell Programming and Scripting

find string nth occurrence in file and print line number

Hi I have requirement to find nth occurrence in a file and capture data from with in lines (between lines) Data in File. <QUOTE> <SESSION> <ATTRIBUTE NAME='Parameter Filename' VALUE='file1.parm'/> <ATTRIBUTE NAME='Service Name' VALUE='None'/> </SESSION> <SESSION> <ATTRIBUTE... (6 Replies)
Discussion started by: tmalik79
6 Replies

6. Shell Programming and Scripting

awk - find number in string

I am trying to go through a file that has a few million lines. I want to only pull lines that contain a number anywhere in the ninth field, but it has to be after a "/" character. Here is my awk: awk -F\| '$9 ~ /\/*{1,}*/ {print $0}' file1 > file2 However, it is just printing out every... (3 Replies)
Discussion started by: dagamier
3 Replies

7. Shell Programming and Scripting

awk find and print next string

Can I do this in one awk session. Solution I have is poor. I want to return the number after PID. echo "Start: 12345 is used by PID:11111 username" | awk -F: '{print $3}' | awk '{print $1}' (6 Replies)
Discussion started by: u20sr
6 Replies

8. Shell Programming and Scripting

Print String N times the number before it

Hey All, I want want to print a string N times the number N before it. Like i have "20 hello". so i want to print hello hello hello . . . . . 20 times.. Please help me.. I am not able o figure out.. how to do the same? (8 Replies)
Discussion started by: jaituteja
8 Replies

9. Shell Programming and Scripting

Find a string and print all lines upto another string

Ok I would like to do the following file test contains the following lines. between the lines ABC there may be any amount of lines up to the next ABC entry. I want to grep for the filename.txt entry and print the lines in between (and including that line) up to and including the last line... (3 Replies)
Discussion started by: revaroo
3 Replies

10. Shell Programming and Scripting

awk to find number in a field then print the line and the number

Hi I want to use awk to match where field 3 contains a number within string - then print the line and just the number as a new field. The source file is pipe delimited and looks something like 1|net|ABC Letr1|1530||| 1|net|EXP_1040 ABC|1121||| 1|net|EXP_TG1224|1122||| 1|net|R_North|1123|||... (5 Replies)
Discussion started by: Mudshark
5 Replies
STRTOL(3)						     Linux Programmer's Manual							 STRTOL(3)

NAME
strtol, strtoll, strtoq - convert a string to a long integer SYNOPSIS
#include <stdlib.h> long int strtol(const char *nptr, char **endptr, int base); long long int strtoll(const char *nptr, char **endptr, int base); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): strtoll(): XOPEN_SOURCE >= 600 || _BSD_SOURCE || _SVID_SOURCE || _ISOC99_SOURCE || _POSIX_C_SOURCE >= 200112L; or cc -std=c99 DESCRIPTION
The strtol() function converts the initial part of the string in nptr to a long integer value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0. The string may begin with an arbitrary amount of white space (as determined by isspace(3)) followed by a single optional '+' or '-' sign. If base is zero or 16, the string may then include a "0x" prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is '0', in which case it is taken as 8 (octal). The remainder of the string is converted to a long int value in the obvious manner, stopping at the first character which is not a valid digit in the given base. (In bases above 10, the letter 'A' in either upper or lower case represents 10, 'B' represents 11, and so forth, with 'Z' representing 35.) If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns 0). In particular, if *nptr is not '' but **endptr is '' on return, the entire string is valid. The strtoll() function works just like the strtol() function but returns a long long integer value. RETURN VALUE
The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol() returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX). ERRORS
EINVAL (not in C99) The given base contains an unsupported value. ERANGE The resulting value was out of range. The implementation may also set errno to EINVAL in case no conversion was performed (no digits seen, and 0 returned). CONFORMING TO
strtol() conforms to SVr4, 4.3BSD, C89, C99 and POSIX.1-2001, and strtoll() to C99 and POSIX.1-2001. NOTES
Since strtol() can legitimately return 0, LONG_MAX, or LONG_MIN (LLONG_MAX or LLONG_MIN for strtoll()) on both success and failure, the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a nonzero value after the call. In locales other than the "C" locale, other strings may also be accepted. (For example, the thousands separator of the current locale may be supported.) BSD also has quad_t strtoq(const char *nptr, char **endptr, int base); with completely analogous definition. Depending on the wordsize of the current architecture, this may be equivalent to strtoll() or to strtol(). EXAMPLE
The program shown below demonstrates the use of strtol(). The first command-line argument specifies a string from which strtol() should parse a number. The second (optional) argument specifies the base to be used for the conversion. (This argument is converted to numeric form using atoi(3), a function that performs no error checking and has a simpler interface than strtol().) Some examples of the results produced by this program are the following: $ ./a.out 123 strtol() returned 123 $ ./a.out ' 123' strtol() returned 123 $ ./a.out 123abc strtol() returned 123 Further characters after number: abc $ ./a.out 123abc 55 strtol: Invalid argument $ ./a.out '' No digits were found $ ./a.out 4000000000 strtol: Numerical result out of range Program source #include <stdlib.h> #include <limits.h> #include <stdio.h> #include <errno.h> int main(int argc, char *argv[]) { int base; char *endptr, *str; long val; if (argc < 2) { fprintf(stderr, "Usage: %s str [base] ", argv[0]); exit(EXIT_FAILURE); } str = argv[1]; base = (argc > 2) ? atoi(argv[2]) : 10; errno = 0; /* To distinguish success/failure after call */ val = strtol(str, &endptr, base); /* Check for various possible errors */ if ((errno == ERANGE && (val == LONG_MAX || val == LONG_MIN)) || (errno != 0 && val == 0)) { perror("strtol"); exit(EXIT_FAILURE); } if (endptr == str) { fprintf(stderr, "No digits were found "); exit(EXIT_FAILURE); } /* If we got here, strtol() successfully parsed a number */ printf("strtol() returned %ld ", val); if (*endptr != '') /* Not necessarily an error... */ printf("Further characters after number: %s ", endptr); exit(EXIT_SUCCESS); } SEE ALSO
atof(3), atoi(3), atol(3), strtod(3), strtoul(3) COLOPHON
This page is part of release 3.44 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/. GNU
2010-09-20 STRTOL(3)
All times are GMT -4. The time now is 08:33 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy