0

Lets say there is a file in linux which has lines which are space separated.

e.g.

This is linux file
This is linux text
This is linux file 1
This is linux file 3

Now I want to only print those rows which has 5th column present in the lines of file. In this example my output should be 3rd and 4th line ( with 1 and 3 as 5th column )

What is the best way to do it?

Peter G.
  • 14,786
  • 7
  • 57
  • 75
  • Why was this question marked as a duplicate for one requesting help with `awk` when this question does not mention, or request, help with `awk`? – David C. Rankin Sep 09 '16 at 13:48

2 Answers2

0

This can be done with awk and its NF (number of fields) variable, as per the following transcript:

pax$ cat inputFile 
This is linux file
This is linux text
This is linux file 1
This is linux file 3

pax$ awk 'NF >= 5 {print}' inputFile 
This is linux file 1
This is linux file 3

This works because the basic form of an awk command is pattern { action }.

The pattern selects those lines (and sometimes things that aren't lines, such as with BEGIN and END patterns) which meet certain criteria and the action dictate what to do.

In this case, it selects lines that have five or more fields and simply prints them.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
0

In addition to awk, you can also do it very simply in bash (or any of the shells) by reading each line into at least five fields, and then checking to insure the fifth field is populated. Something like this will work (it will read from the filename given as the first argument (or stdin if no name is given))

#!/bin/bash

fn="${1:-/dev/stdin}"

while read -r f1 f2 f3 f4 f5; do
    [ -n "$f5" ] && printf "%s %s %s %s %s\n" "$f1" "$f2" "$f3" "$f4" "$f5"
done <"$fn"

Example

Using your data, the snippet above produces the following output:

$ bash prn5flds.sh dat/5fields.txt
This is linux file 1
This is linux file 3

(note: depending your your shell, read may or may not support the -r option. If it doesn't, simply omit it)

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85