3

I am trying to run a script that uses awk. There is no error it seems, but it doesn't create the file that I want. This is the script:

#!/bin/bash

echo "Number of domain:"
read number
echo "Domain name:"
read domain
more "file.txt" | awk '$2=='$domain' {print $1, "1.0"} $2!='$domain' {print $1,"-1.0"}' >"$number_domain.txt"
echo "DONE"

Basically, I want to create a document leaving all $1 that are, and changing $2, if it is $domain, write 1.0, else -1.0.

I am confused about how you can write the text with " " or ' ' and the awk ' ' and " ".

  • 5
    Why do you more "file.txt" | awk... ? Also, on the right side of the page, under Related there are several links about "passing shell variables to awk" – don_crissti Jun 28 '16 at 19:26
  • 1
    What exactly are you confused about " " and ' '? What output do you get and what is the expected output? – Paradox Jun 28 '16 at 19:30
  • @don_crissti I'll be sure to remove those in the future - I appreciate you clearing the confusion for me. – Paradox Jun 28 '16 at 19:34
  • actually I had no output. I don't know why – cloudy_fog Jun 28 '16 at 19:55
  • First: Change more file.txt | awk to cat file.txt | awk (or better yet, use redirection). Second: I think you need a ';' after that first '}' since those look like separate statements to me. Third, and most importantly, do what Thomas Dickey said. – Edward Falk Jun 29 '16 at 1:49
4

The last item on this line

more "file.txt" | awk '$2=='$domain' {print $1, "1.0"} $2!='$domain' {print $1,"-1.0"}' >"$number_domain.txt"

is probably intended to be

>"${number}_${domain}.txt"

corresponding to the two variables which your script reads. It would be nice if your script also ensured that the variables are not empty strings. If they are empty, then the awk script will misbehave.

  • This is the correct answer. – Edward Falk Jun 29 '16 at 2:00
3

To use shell variables in awk give them to the awk script using -v awkvariable="$shellvariable" instead of trying to paste them into the script itself, i.e.

awk -v d="$domain" '$2 == d { print $1, "1.0" } $2 != d { print $1,"-1.0" }'

This would "import" the value $domain into the awk script as the value of the variable d.

If the script in doing the right thing or not, I don't know, but you might want to use ${number} rather than $number in the redirection afterwards. There is no variable called number_domain in your script, i.e. ... >"${number}_$domain.txt".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.