Specify the field to search for a string in the Linux shell script

Asked 2 years ago, Updated 2 years ago, 68 views

I don't know how to do it.

Number | Name | Height | Weight
There is a table that records the .

I would like to extract people over 170 centimeters tall and under 180 centimeters from here.

 grep$a filename

I put 170 or 180 height in $a and turned it around with while to search
In some cases, the exact value of the weight cannot be obtained by using this method.
(People weighing 170 kilograms were extracted.)
So I want to search by column specification, but I can't think of a way to do it.

Please let me know if there is a good way.

linux shellscript

2022-09-30 18:57

2 Answers

awk-F\|'$3>=170&&$3<=180{print$0}'data.txt

I see.

-F\| delimiter specification, where | is recognized as a pipe, so escape with \.

For each line,
$3>=170&$3<=180| When the third field separated by $3> 170170&$3< br180 is between 170 and 180...
{print$0}View $0 (whole line)

The behavior is


2022-09-30 18:57

It's called a "shell script", so if you dare to use IFS to specify the delimiter instead of awk.

is_height_in_range(){
  localmin = $1
  local max = $2
  local line = "$3"

  IFS="|"
  set--${line}
  ["$3"-ge "$min"] & ["$3"-le "$max"]
  return
}

IFS =
while read line;do
  is_height_in_range170 180"$line"||continue
  printf'%s\n'"$line"
done

local I'm using it, so it's not POSIX compatible, but I think most shells work.

If read returns a non-zero status, it will exit the while loop, so if there is no new line at the end of the file, the last line will be ignored, but simplicity was prioritized because it is not the essence of the answer.


2022-09-30 18:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.