ComeRun
ComeRun

Reputation: 921

Bash to print a Nth word if an specific string exists

In IHS access log I need to grab a info line by line iff there is a 401 response.

The following is the format and I need to go through the log line by line to grab a specific number in front of the user property (which in this example is 123 or 432) only when there is 401 response found on the line.

something like, if nth word of the line is 401 the from the nth column grab the number and print it.

 myhost.com xxx.x.xxx.x aaa.aa.aa.aaa - - [14/Aug/2013:10:44:55 +1000] "GET /http/user=123 HTTP/1.1" 401 55 "-" "Apache-HttpClient/4.2.3 (java 1.5)" 21293 80 0
 myhost.com xxx.x.xxx.x aaa.aa.aa.aaa - - [14/Aug/2013:10:45:55 +1000] "GET /http/user=432 HTTP/1.1" 401 55 "-" "Apache-HttpClient/4.2.3 (java 1.5)" 21293 80 0

Upvotes: 0

Views: 238

Answers (2)

Alec
Alec

Reputation: 1188

perl -F'\s|=' -lane 'print $F[9] if $F[11] == 401' your_file.txt

Upvotes: 0

Prince John Wesley
Prince John Wesley

Reputation: 63688

Tokenize the record by whitespace or '=' sign and print the 10th field if the 12th field is 401.

awk -F' |=' '$12 ~/401/{print $10}' inputFile

Upvotes: 1

Related Questions