I've a file as follows:
This is a test.
One bang two three
Foo dang Bar
001 0xfg 0xA
002 0xA foo bar 0xfG
I'm done
| Tutorial details | |
|---|---|
| Difficulty | Intermediate (rss) |
| Root privileges | No |
| Requirements | sed and bash/ksh |
How do I delete all "words" from the above file which ends with a particular letter (say 'g') in each line? The output should be as follows:
This is a test.
One two three
Foo Bar
001 0xA
002 0xA foo bar
I'm done
How do I delete regex-based word using sed or awk under Linux / Unix like operating systems?
You can use any standard Unix text editing and processing utility to find and replace/delete words from the file.
Sed example
The syntax is:
sed 's/\<word\>//g' input sed -e 's/\<regex-for-word\>//g' input > output
In this example, delete foo word from input:
echo 'This is a foo test' | sed -e 's/\<foo\>//g'
To delete all words ending with a letter 'g' in each line, enter:
sed -e 's/\<[a-zA-Z0-9]*[g|G]\>//g' input
Awk example
The syntax is:
awk '{gsub("word", "");print}' input awk '{gsub("regex", "");print}' input > output
In this example, delete bar word from input:
awk '{gsub("bar", "");print}' <<< "This is a bar test"
To delete all words ending with a letter 'g' in each line using gnu/awk, enter:
awk '{gsub("[a-zA-Z0-9]*[g|G]$", "");print}' input
Or
awk '{gsub("\\<[a-zA-Z0-9]*[g|G]\\>", "");print}' input
You should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop













{ 5 comments… read them below or add one }
The awk examples do not do what they are supposed to do; they delete all matching strings, not matching words.
echo 'Tough thing rough' | awk '{gsub("[a-zA-Z0-9]*[g|G]", "");print}' h hTough and rough do not end in ‘g’
echo 'Tough thing rough' | awk '{gsub("[a-zA-Z0-9]*[g|G]$", "");print}'Yes, $ missing at the end of regex. The faq has been updated. Thanks for the head up.
Hi,
Very useful article.
Thanks a lot…
Thanks for sharing the nifty regex :)