QMG
QMG

Reputation: 749

AWK how to read a line from file and get some value using substring

I am new to AWK. Can you please let me know how to read a line from file using awk? How can I get a value using substring function from read line and store it into a variable? For example here is the data set:

01 001   410070300186169                 359829047319420
01 002   410070234186169                 359829043245420
01 001   410070234186169                 359829047319420

I want to check if at position 4 to 6 , value is "001" then write the data in file file_1 and if the value is "002" then write the data in file file_2.

Upvotes: 1

Views: 2847

Answers (3)

sampson-chen
sampson-chen

Reputation: 47317

Here you go; you can put this all on one line, but I've broken it down into multiple for readability:

awk '$2=="001" {print > "file_1"}
     $2=="002" {print > "file_2"}' input_file

Explanation:

  • awk separates each line into fields using spaces and tabs as delimiters by default, so for each line read, values in your 2nd column will be saved in $2
  • $2=="001" {print > "file_1"}: if $2 is 001, print the entire line into file_1
  • $2=="002" {print > "file_2"}: likewise for 002

Upvotes: 2

anubhava
anubhava

Reputation: 785651

You can do all that in awk 1 liner like this:

awk '$2 == "001" {print > "file_1"} $2 == "002" {print > "file_2"}' infile

Upvotes: 1

pbhd
pbhd

Reputation: 4467

You can read into $0 with

getline <file

then you can use

 substr($0, 1 , 5)

to get a substring of $0 starting at index 1 with length 5

Upvotes: 0

Related Questions