[SOLVED] nawk FS using pipe read variables from file

I have a file data_1.out which contains:

1|abc mail|mail subject|mail body
2|def mail|mail subject|def mail body

I am trying to read the variables from data_1.out and use them to print to 2 different files based on the id (first_column)
The problem is I am not able to read the file using FS in the nawk. Could some help me out. If I substitute the "|" with space in data_1.out below thing works.

nof=`wc -l data_1.out | awk ' { print $1 }'`
no_of_lines=`expr $nof - 0`
z=1

while [[ $z -le $no_of_lines ]]
do

cat data_1.out | nawk -v I="$z" 'NR==I { print $0 }' | read id mail_id mail_subject mail_body

printf "From: abc@unix.com
To: ${mail_id}
Subject: IDI : ${mail_subject}
${mail_body} " >> m_file_${id}.out

z=$((z + 1))
done

Thanks for your help.

You don't need awk at all here, or wc, or expr, or backticks. You can do this all in one while read loop.

while IFS="|" read ID MAIL_ID MAIL_SUBJECT MAIL_BODY
do
        cat <<EOF >> m_file_${ID}.out
From: abc@unix.com
To: ${MAIL_ID}
Subject: IDI : ${MAIL_SUBJECT}
${MAIL_BODY}
EOF
done

Or if you want to keep your script try:

 
sed 's/|/ /g' data_1.out | awk -v I="$z" 'NR==I { print $0 }' | read id mail_id mail_subject mail_body

read at the end of the pipe does not work in most bourne shell, only KSH.

You can use -F"|" on awk instead of sedding | to space.

I tried using the -F"|", but it doesn't seem to work.

I have tried the while IFS but it is not exiting the loop.

is read working on your machine..

lets try...(not tested this code..) Hope this works...:slight_smile:

while read line
do
echo $line | awk  -F "|" '{ print $0 }' OFS=" " | read id mail_id mail_subject mail_body

printf "From: abc@unix.com
To: ${mail_id}
Subject: IDI : ${mail_subject}
${mail_body} " >> m_file_${id}.out

done<input_file

That final EOF needs to be at the beginning of the line, you can't indent it.

If that doesn't help, show your code please.

1 Like

Thanks, Got it working...

read at the end of the pipe does not work in most bourne shell, only KSH.