mohammad
mohammad

Reputation: 531

put awk code in bash and sort the result

I have a awk code for combining 2 files and add the result to the end of file.txt using ">>"

my code

NR==FNR && $2!=0 {two[$0]++;j=1; next }{for(i in two) {split(i,one,FS); if(one[3] == $NF){x=$4;sub( /[[:digit:]]/, "A", $4); print j++,$1,$2,$3,x,$4 | "column -t" ">>" "./Desktop/file.txt"}}}

i want put my awk to bash script and finaly sort my file.txt and save sorted result to file.txt again using >

i tried this

#!/bin/bash
command=$(awk '{NR==FNR && $2!=0 {two[$0]++;j=1; next }{for(i in two) {split(i,one,FS); if(one[3] == $NF){x=$4;sub( /[[:digit:]]/, "A", $4); print $1,$2,$3,$4 | "column -t" ">>" "./Desktop/file.txt"}}}}')
echo -e "$command" | column -t | sort -s -n -k4 > ./Desktop/file.txt 

but it gives me error "for reading (no such a file or directory)"

where is my mistake?

Thanks in advance

Upvotes: 0

Views: 377

Answers (1)

Ed Morton
Ed Morton

Reputation: 204578

1) you aren't specifying the input files for your awk script. This:

command=$(awk '{...stuff...}')

needs to be:

command=$(awk '{...stuff...}' file1 file2)

2) You move your awk condition "NR == ..." inside the action part so it will no longer behave as a condition.

3) Your awk script output is going into "file.txt" so "command" is empty when you echo it on the subsequent line.

4) You have unused variables x and j

5) You pass the arg FS to split() unnecessarily.

etc...

I THINK what you want is:

command=$( awk '
   NR==FNR && $2!=0 { two[$0]++; next }
   {
      for(i in two) {
          split(i,one)
          if(one[3] == $NF) {
             sub(/[[:digit:]]/, "A", $4)
             print $1,$2,$3,$4 
          }
      }
    }
' file1 file2 )
echo -e "$command" | column -t >> "./Desktop/file.txt"
echo -e "$command" | column -t | sort -s -n -k4 >> ./Desktop/file.txt

but it's hard to tell.

Upvotes: 1

Related Questions