3

I want to print the whole line with specific column started count variable in text.

  • file.log format
1 101010 101010 4.0001 my home
2 101010 101010 5.0001 my home
3 101010 101010 6.0001 my home
4 101010 101010 7.0001 my home
  • my script
count=4
awk -v cnt="$count" '$4 ~ /^[cnt]\./' file.log
  • I want this result.
1 101010 101010 4.0001 my home
  • But my result is nothing....

Please tell me the wrong point of my script.

ccjason
  • 31
  • 1
  • 1
    FYI `[cnt]` is a bracket expression which means "a single character which is either of the letters c, n, or t". See https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap09.html#tag_09_03_05. – Ed Morton Dec 12 '20 at 18:57

2 Answers2

3

You need NOT to use awk variable in a literal regexp, use int function here to convert 4th field as interger and then compare it directly with variable like:

count="4"
awk -v cnt="$count" 'int($4)==cnt' Input_file

Explanation: First passing shell variable count to cnt as an awk variable. Then using int function on 4th field to get only integer part eg--> from 4.0001 to 4 to make an exact comparison with cnt and once its equal it will print that line.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
2

You could use a dynamic (aka computed) instead of literal regexp:

awk -v cnt="$count" '$4 ~ ("^" cnt "[.]")' file.log

See How do I use shell variables in an awk script? and https://www.gnu.org/software/gawk/manual/gawk.html#Computed-Regexps.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185