Read the lines from a file in Bash and parse the words in variables for mailx parameters

I have a bash script that reads lines from a text file with 4 columns (no headers). The number of lines can be no more than 4 lines or less. Words on each line are separated by a SPACE character.

ab@from.com xyz@to.com ; abc@to.com Sub1 MailBody1 xv@from.com abc@to.com ; poy@to.com Sub2 MailBody2 mb@from.com gmc@to.com ; abc@to.com Sub3 MailBody3 yt@from.com gqw@to.com ; xyz@to.com Sub4 MailBody4 

I am currently parsing a file and, having received each line, I store each word in each line in a variable and call mailx four times. Wonder if there is an elegant awk / sed solution for the logic below.

  • find the total number of rows
  • while read $line , save each line in a variable
  • parse each line as i=( $line1 ) , j=( $line2 ) , etc.
  • receive values ​​from each row as ${i[0]} , ${i[1]} , ${i[2]} and ${i[3]} , etc.
  • call mailx -s ${i[2]} -t ${i[1]} -r ${i[0]} < ${i[3]}
  • parse the next line and call mailx
  • do this until more lines are reached or a maximum of 4 lines.

Does awk or sed provide an elegant solution to the above iteration / looping logic?

+4
source share
2 answers

Take a picture:

 head -n 4 mail.txt | while read from to subject body; do mailx -s "$subject" -t "$to" -r "$from" <<< "$body" done 
  • head -n 4 reads up to four lines from your text file.
  • read can read multiple variables from one line, so we can use named variables for readability.
  • <<< probably you want to redirect, not < . Maybe.
+4
source

The above while loop works well as a simple alternative to sed and awk if you have a lot of control over the display of lines of text in a file. The read command can also use the specified delimiter using the -d flag.

Another simple example:

I used mysql to capture a list of users and hosts by placing it in the / tmp / userlist file with text as shown:

 user1 host1 user2 host2 user3 host3 

I passed these variables to the mysql command to get the information about the provision of data for these users and hosts and add to / tmp / grantlist:

 cat /tmp/userlist | while read user hostname; do echo -e "\n\nGrabbing user $user for host $hostname..." mysql -u root -h "localhost" -e "SHOW GRANTS FOR '$user'@$hostname" >> /tmp/grantlist done 
+2
source

All Articles