Delete string from line that matches regex with AWK

Viewed 642

I have file that contains a lot of data like this and I have to delete everything that matches this regex [-]+\d+(.*)

Input:

zxczxc-6-9hw7w
qweqweqweqweqwe-18-8c5r6
asdasdasasdsad-11-br9ft

Output should be:

zxczxc
qweqweqweqweqwe
asdasdasasdsad

How can I do this with AWK?

3 Answers

AFAIK awk doesn't support \d so you could use [0-9], your regex is correct only thing you need to put it in correct function of awk.

awk '{sub(/-+[0-9].*/,"")} 1'  Input_file

You don't need the extra <plus> sign afther [0-9] as this is covered by the .*

sed might be easier...

$ sed -E 's/-+[0-9].*//' file

note that .* covers +.*

Generally, if you want to delete a string that matches a regular expression, then all you need to do is substitute it with an empty string. The most straightforward solution is sed which is presented by karafka, the other solution is using awk as presented by RavinderSingh13.

The overall syntax would look like this:

sed -e 's/ere//g' file
awk '{gsub(/ere/,"")}1' file

with ere the regular expression representation. Note I use g and gsub here to substitute all non-overlapping strings.

Due to the nature of the regular expression in the OP, i.e. it ends with .*, the g can be dropped. It also allows us to write a different awk solution which works with field separators:

awk -F '-+[0-9]' '{print $1}' file
Related