Lex code to replace a word with another word in a file
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:
/* LEX code to replace a word with another taking input from file */ /* Definition section *//* variable replace_with and replace can be accessed inside rule section and main() */ %{ #include<stdio.h> #include<string.h> char replace_with [] = "Best"; char replace [] ="A"; %} /* Rule Section *//* Rule 1 compares the matched token with the word to replace and replaces with another word on successful match else simply writes the content of input file to output file *//* Rule 2 matches everything other than string like whitespace, digits, special symbols etc and writes it to output file */ %% [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; } /* code section */int main() { extern FILE *yyin, *yyout; /* open the input file in read mode */ yyin=fopen("input.txt", "r"); /* open the output file in write mode */ yyout=fopen("output.txt", "w"); yylex(); } |
Output:

Output file: output.txt

Recommended Posts:
- Lex program to search a word in a file
- Lex program to count the frequency of the given word in a file
- How to Prepare a Word List for the GRE General Test
- Lex program to find the length of the longest word
- LEX code to extract HTML tags from a file
- Lex program to copy the content of one file to another file
- Why Kotlin will replace Java for Android App Development
- Hackathon - Think, Code, Create
- Three address code in Compiler
- Code Injection and Mitigation with Example
- Making a QR code for a website
- Google Summer of Code Preparation
- Issues in the design of a code generator
- Packaging and Publishing Python code
- Compiler Design | Code Optimization
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



