sentientmachine
sentientmachine

Reputation: 357

Can't explain Awk behaviour

I'm new in bash scripting. In my script I need to remove lines not beginning with the 'a' character from a text file, writing these lines in temp.txt file. I'm using this syntax of awk to do the job.

read value
awk '($1 != "$value" ) ' file1.txt > temp.txt

When I run the script it says at the beginning all the lines which don't begin with the value, and then the lines beginning with the value. Can someone explain to me why this happens and eventually suggest me a correction?

Upvotes: 0

Views: 37

Answers (2)

hek2mgl
hek2mgl

Reputation: 157992

Basically you can use grep:

grep -v '^a' file1 > file2

^ matches the beginning of the line. ^a matches an a at the beginning of the line. -v negates the match meaning grep will output all lines which does not start with an a.

If you want to pass a variable to that command, you'll need to use double quotes instead of single quotes:

grep -v "^$value" file1 > file2

But be aware of the fact that $value will get interpreted as a regular expression. Meaning if value=. for example, it would match any character, not just the literal ..

To circumvent that, awk comes in mind again and that's my final suggestion:

awk -v value="$value" 'substr($0,0,length(value)) != value' file1 > file2

Upvotes: 1

choroba
choroba

Reputation: 241868

Variables aren't expanded in single quotes. What your script does is it excludes all lines starting with the string $value literally followed by whitespace.

Upvotes: 1

Related Questions