Link to home
Start Free TrialLog in
Avatar of bje
bjeFlag for United States of America

asked on

how to use awk and sed in the same command

Trying to use awk and sed together

Have a file and would like to pull out of the file a value and put into a variable.

this is what i have.  need to remove the spaces in the vaule

name=$(awk -F"," 'NR==18 {print $2}' | sed 's/ //g' $file )
ASKER CERTIFIED SOLUTION
Avatar of MikeOM_DBA
MikeOM_DBA
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of woolmilkporc
If you want to keep using your version do it this way:

name=$(awk -F"," 'NR==18 {print $2}' $file | sed 's/ //g' )

$file is a parameter to awk, sed just reads from stdin here and thus doesn't need a filename.

But pure awk as suggested by MikeOM_DBA is certainly better!
I certainly prefer Mike's solution (I keep on seeing sequences of sed, grep, tail, awk and others in scripts, thinking that a simple awk script would do all of that in one go).

I think there's a bit missing from the solution though - a trailing ")" and the "print $2":
name=$(awk -F"," 'NR==18 {gsub(/ /,"",$2); print $2 }' $file)

Open in new window

Thanks simon, It's Friday dyslexia!
Avatar of bje

ASKER

is cut the best way to determine the first position of a value

so for my variable name, will need to pull out the first position and put into a variable and if it begins with a 4 then do something.

first=$(cut -c1 $name)
 if $first = 4
  then
     do something
 else
    do something
fi
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bje

ASKER

I've requested that this question be closed as follows:

Accepted answer: 200 points for woolmilkporc's comment #a40767584
Assisted answer: 150 points for woolmilkporc's comment #a40767044
Assisted answer: 150 points for simon3270's comment #a40767464
Assisted answer: 0 points for bje's comment #a40767577

for the following reason:

Thank you
Mike should have the points for #40767023 - all I did in #a40767464 was add a small missing section - the idea of sticking with just awk was his.
Avatar of bje

ASKER

My apologies for the confusion.  Thank you