1

My requirement is to split a file based on the first field. My file looks something like this :

aaa|12345
bbb|45679
aaa|334564
ccc|qewqw

Now my awk command works just fine and splits the file with respect to the first field value.

awk -F\| '{f=($1); print $2 > f}' /myfile 

Result : File name aaa has the below rows :

12345
334564

Now , I want to make it input driven , that is from a script i will enter the value aaa to this awk command and it will match with $1 and create the file like above. I tried with awk -v to take the value as input, but its not working the way I want it to. Any help would be much appreciated.

Thanks in advance.

brarjun
  • 23
  • 4
  • Will this answer your need?: https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script – James Brown May 12 '20 at 06:40
  • What "no working" means? Can you show code and error message? – rpoleski May 12 '20 at 06:46
  • I tried these options , but the things is it's not doing the matching correctly . I mean if I pass a value 'v' the entire file content is saved under value 'v' which I don't want. @James Brown – brarjun May 12 '20 at 06:47
  • There is no way to tell you what you're doing wrong, if you're not showing the code. – rpoleski May 12 '20 at 06:51
  • this is what I am try to do : awk -v "var=$input_value" -F\| '{f=($var); print $2 > f}' /myfile . But here I am not sure of how to compare the $1 value with var as a result the entire file content is moved to var. – brarjun May 12 '20 at 06:54

3 Answers3

1

Like this?:

$ awk -v f=aaa -F\| 'f==$1{print $2 > f}' file
$ ls
aaa file
$ cat aaa
12345
334564

Explained:

$ awk -v f=aaa -F\| '     # set input field separator and var f="aaa"
f==$1 {                   # if f ie. "aaa" equals to first field value
    print $2 > f          # write second field value to file f ie. "aaa"
}' file
James Brown
  • 36,089
  • 7
  • 43
  • 59
  • can you please explain, where $1 and aaa are compared and only values corresponding to $1=aaa are retrieved in this code, sorry but I am new to this, so may be I am asking basic questions. – brarjun May 12 '20 at 06:59
  • 1
    `-v f=aaa` passes string `aaa` to variable `f`. `$1~f` is the matching, now that I had my morning coffee I see that it's faulty, you should use `f==$1`, I'll fix it. – James Brown May 12 '20 at 07:27
0
awk -v var=$input_value -F\| '{print $2 > var}' myfile

In your code in comments the problem is with f=($var). I think you wanted f=var.

rpoleski
  • 988
  • 5
  • 12
0
cat file | awk -v inp=aaa -F\| '$1 ~ inp { print $2 > inp }'
Aakash Wadhwa
  • 91
  • 1
  • 2
  • 11