hibbijibbies
hibbijibbies

Reputation: 13

Reading input file and inserting text into output file

I have an input file called "namelist.txt" with email addresses:

[email protected]
[email protected]
[email protected]

I am trying to read the addresses from this input file and inserting their values into an output file (newfile.txt) that should read:

user "[email protected]" with pass"pass" is "[email protected]" here
user "[email protected]" with pass"pass" is "[email protected]" here
user "[email protected]" with pass"pass" is "[email protected]" here

The closest I have come is by using awk:

awk '{print "user $0 there with pass"pass" is user $0 here"}' < namelist.txt > newfile.txt

This however prints the following:

user $0 there with pass is user $0 here 
user $0 there with pass is user $0 here
user $0 there with pass is user $0 here

This doesn't print the variable values nor the "pass" value.

I don't know where I am going wrong or whether I am even on the right track, so any advice and / or pointers would be greatly appreciated.

EDIT:

Using:

awk '{print "user \""$0"\" there with pass \"pass\" is user \""$0"\" here}' file

results in the following output on Ubuntu (14.04.2 LTS):

" heree with pass "pass" is user "[email protected]
" heree with pass "pass" is user "[email protected]
" heree with pass "pass" is user "[email protected]

Abovementioned code works fine in a UNIX terminal but not in Ubuntu nor Raspberry Pi.

I am confused as to why the differences between distros.

Upvotes: 1

Views: 64

Answers (2)

123
123

Reputation: 11216

The $ variable needs to be outside of quotes and you need to escape the quotes you want to see.

awk '{print "user \""$0"\" there with pass\"pass\" is user \""$0"\" here"}' file

user "[email protected]" there with pass"pass" is user "[email protected]" here
user "[email protected]" there with pass"pass" is user "[email protected]" here
user "[email protected]" there with pass"pass" is user "[email protected]" here

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 203532

You had included the text $0 inside the literal string but in any case when inserting input data into some formatted string for output, it's usually clearest and easiest to enhance in future if you use printf instead of print:

$ awk '{printf "user \"%s\" there with pass \"pass\" is user \"%s\" here\n", $0, $0}' file
user "[email protected]" there with pass "pass" is user "[email protected]" here
user "[email protected]" there with pass "pass" is user "[email protected]" here
user "[email protected]" there with pass "pass" is user "[email protected]" here

and don't use input redirection with awk as that removes the ability for the script to access the input file name. awk is perfectly capable of opening files itself.

Upvotes: 2

Related Questions