awk redict to diferent files by matched pattern & excuting replace before redirecting

Viewed 40

In my input file, each row of its first column contains either "pattern1" or "pattern2". I want to split it into file1 and file2 depends on the pattern, but remove the "pattern" in the split files. Below is how I wrote the awk script, but I got the following error, can anyone help? Thanks!

prefix=test

awk -F '\t' -v file1=${prefix}.pattern1 -v file2=${prefix}.pattern2 '{if($1 ~ /pattern1/) { gsub("pattern1", "", $1); print >> (file1) }; else {gsub("pattern2", "", $1); print > (file2)' ${prefix}.input


awk: cmd. line:1: {if($1 ~ /pattern1/) { gsub("pattern1", "", $1); print >> (file1) }; else {gsub("pattern2", "", $1); print >> (file2)
awk: cmd. line:1:                                                                                                                     ^ unexpected newline or end of string
2 Answers

You may use:

prefix=test

awk -v file1="$prefix.pattern1" -v file2="$prefix.pattern2" '
BEGIN { FS=OFS="\t" }
{
    out = ""
    if ($1 ~ /pattern1/)
       out = file1
    if ($1 ~ /pattern2/)
       out = file2
}
out {
    gsub(/pattern1|pattern2/, "", $1)
    print > out
}' "$prefix.input"

Add some indentation and the reason for the error becomes clear

awk -F '\t' -v file1=${prefix}.pattern1 -v file2=${prefix}.pattern2 '
    {
        if($1 ~ /pattern1/) {
            gsub("pattern1", "", $1); print >> (file1)
        }; else {
            gsub("pattern2", "", $1); print > (file2)
' ${prefix}.input

Related