Lex code to replace a word with another word in a file
Last Updated :
30 Sep, 2022
Given a text file as input, the task is to replace a given word with another word in the file.
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt.
Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Prerequisite: Flex (Fast lexical Analyzer Generator)
Approach:
As we know, yytext holds the value of current matched token, we can compare it with word to replace. if the value of yytext and word to replace are same, replace the word with another word and write it to the output file otherwise simply copy the content of input file to output file.
Input File: input.txt
Below is the implementation of above approach:
%{
#include<stdio.h>
#include<string.h>
char replace_with [] = "Best" ;
char replace [] = "A" ;
%}
%%
[a-zA-Z]+ { if ( strcmp (yytext, replace)==0)
fprintf (yyout, "%s" , replace_with);
else
fprintf (yyout, "%s" , yytext);}
. fprintf (yyout, "%s" , yytext);
%%
int yywrap()
{
return 1;
}
int main()
{
extern FILE *yyin, *yyout;
yyin= fopen ( "input.txt" , "r" );
yyout= fopen ( "output.txt" , "w" );
yylex();
}
|
Output:
Output file: output.txt
Share your thoughts in the comments
Please Login to comment...