create new file from comparison of two files using awk

June 21, 2012 at 15:03:04
Specs: Linux i686
Reading an old post (http://www.computing.net/answers/unix/comparing-two-files-using-awk/7627.html), would like a variation:

file1
text1, 10
text2, 20

file2
text1textabc, 10
text2textdef, 20
text3textghi, 30

Newfile
text1textabc, 10
text2textdef, 20

The task is to be able to read 'file2' and search for a criterion using regular expression, e.g. '^text'. The script should search 'file1' and where a match occurs print the record in the format of 'file2'.

Thanks in advance.


See More: create new file from comparison of two files using awk

Report •

#1
June 21, 2012 at 23:21:59
Sorry, but I won't do your homework for you, but I'll give you a hint.

Since the link you posted showed you how to build an awk array with one file, this example reads file2 and prints out the line where field 1 starts with text1:

awk ' BEGIN { FS="," }
{
if($1 ~ /^text1/)
   print $0
} ' file2


Report •

#2
June 21, 2012 at 23:33:17
Thanks. Have been reading bash guide and awk tutorial, but have not yet found information about the syntax to use regular expressions.

Hints and correct terms are all that is required! For example, didn't know the quoted post was an example of an array!

Isn't there supposed to be the redirect command at the end of the script, to create the new file?


Report •

#3
June 22, 2012 at 10:31:22
The online GNU Awk Users Guide has a section on using regular expressions:

http://www.gnu.org/software/gawk/ma...


The quoted post mentions in #5 reply that it is an array scan.


Yes, you can create a new file with a redirection arrow:

# redirection works like this:
awk ' BEGIN { FS="," }
{
if($1 ~ /^text1/)
   print $0
} ' file2 > newfile
 

If you posted code and at least tried to make an effort, you'd probably get more help.


Report •
Related Solutions


Ask Question