Here are some examples of how to use AWK for searching file contents and replacing text in a file
Searching file contents:
To search for a specific pattern in a file, you can use the following command:
awk '/pattern/' filename
For example, to search for the word "example" in a file called "file.txt", you would use the following command:
awk '/example/' file.txt
To search for a pattern and print the lines that match, you can use the following command:
awk '/pattern/ { print }' filename
For example, to search for the word "example" in a file called
"file.txt" and print the lines that match, you would use the following
command:
awk '/example/ { print }' file.txt
Replacing text in a file:
To replace a specific pattern with a new text in a file, you can use the following command:
awk '{ gsub(/pattern/, "newtext"); print }' filename
For example, to replace the word "example" with the word "test" in a
file called "file.txt", you would use the following command:
awk '{ gsub(/example/, "test"); print }' file.txt
To replace a pattern and save the changes back to the original file, you can use the following command:
awk '{ gsub(/pattern/, "newtext"); print > "newfile" }' filename
For example, to replace the word "example" with the word "test" in a
file called "file.txt" and save the changes back to the original file,
you would use the following command:
awk '{ gsub(/example/, "test"); print > "file.txt" }' file.txt
No comments:
Post a Comment