bash - Find negative numbers in file with grep -


i have script reads file, file looks this:

711324865,438918283,2 -333308476,886548365,2 1378685449,-911401007,2 -435117907,560922996,2 259073357,714183955,2 ... 

the script:

#!/bin/bash while ifs=, read childid parentid parentlevel        grep "\$parentid" parent_child_output_level2.csv        resul=$?        echo "child $childid, parent $parentid parentlevel $parentlevel resul $resul" done < parent_child_output_level1.csv 

but not working, resul allways returning me 1, false positive.

i know because can launch next command, equivalent, think:

[core@dub-vcd-vms165 generated-and-saved-to-hdfs]$  grep "\-911401007"parent_child_output_level2.csv    -911401007,-157143722,3 

please help.

your title inconsistent question. title asks how grep negative numbers, avinash raj answered well, although i'd suggest don't need (perl-style) look-behind positive assertion (^|,)\k match start-of-field, because if file well-formed, -\d+ match numbers well. run (edit: realized leading - need -- prevent grep taking pattern option):

grep -op -- '-\d+' file.csv; 

your question includes script intention seems to grep number (positive or negative) in first field (childid) of 1 file (parent_child_output_level2.csv) occurs in second field (parentid) of file (parent_child_output_level1.csv). accomplish this, wouldn't use grep, because you're trying exact numerical equality test, can done exact string equality test assuming numbers consistently represented (e.g. no redundant leading zeroes). repeatedly grepping through entire file search number in 1 column wasteful of cpu.

here's do:

parentidlist=($(cut -d, -f2 parent_child_output_level1.csv)); childidlist=($(cut -d, -f1 parent_child_output_level2.csv)); parentid in "${parentidlist[@]}";     childid in "${childidlist[@]}";         if [[ "$childid" == "$parentid" ]];             echo "$parentid";         fi;     done; done; 

with approach, precompute both parent id list , child id list once, using cut extract appropriate field each file. can use shell-builtin loop, shell-builtin if conditional, , shell-builtin [[ test command accomplish check, , finish shell-builtin echo print matches. shell-builtin, after initial command substitutions run cut external executable.

if also want filter these results on negative numbers, grep ^- in results of above script, or grep in results of each (or first) cut command, or add following line inside outer loop:

if [[ "${parentid:0:1}" != '-' ]]; continue; fi; 

alternative approach:

if [[ "$parentid" != -* ]]; continue; fi; 

either approach skip non-negatives.


Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -