本文介绍了从Bash中的File读取行并将单词解析为mailx参数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash脚本,该脚本从具有4列(无标题)的文本文件中读取行.行数最多可以为4行或更少.每行中的单词由空格字符分隔.

I have a bash script which reads lines from a text file with 4 columns(no headers). The number of lines can be a maximum of 4 lines or less. The words in each line are separated by SPACE character.

[email protected]   [email protected];[email protected]   Sub1   MailBody1
[email protected]   [email protected];[email protected]   Sub2   MailBody2
[email protected]   [email protected];[email protected]   Sub3   MailBody3
[email protected]   [email protected];[email protected]   Sub4   MailBody4

当前,我正在解析文件,在获取每一行之后,我将每一行中的每个单词存储到一个变量中,并调用mailx四次.想知道是否有一个优雅的awk/sed解决方案来解决以下提到的逻辑.

Currently, I am parsing the file and after getting each line, I am storing each word in every line into a variable and calling mailx four times. Wondering if is there is an elegant awk/sed solution to the below mentioned logic.

  • 查找总行数
  • read $line期间,将每一行存储在一个变量中
  • 将每行解析为i=( $line1 )j=( $line2 )
  • 从每行获取${i[0]}${i[1]}${i[2]}${i[3]}等的值
  • 致电mailx -s ${i[2]} -t ${i[1]} -r ${i[0]} < ${i[3]}
  • 解析下一行并调用mailx
  • 执行此操作,直到没有更多行或最多4行为止
  • find total number of lines
  • while read $line, store each line in a variable
  • parse each line as i=( $line1 ), j=( $line2 ) etc
  • get values from each line 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 next line and call mailx
  • do this until no more lines or max 4 lines have been reached

awk或sed是否为上述迭代/循环逻辑提供了一种优雅的解决方案?

Do awk or sed provide an elegant solution to the above iterating/looping logic?

推荐答案

试一下:

head -n 4 mail.txt | while read from to subject body; do
    mailx -s "$subject" -t "$to" -r "$from" <<< "$body"
done

  • head -n 4最多可从文本文件读取四行.
  • read可以从一行读取多个变量,因此我们可以使用命名变量来提高可读性.
  • <<<可能是您要重定向的内容,而不是<.大概吧.
    • 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.
    • <<< is probably what you want for the redirection, rather than <. Probably.
    • 这篇关于从Bash中的File读取行并将单词解析为mailx参数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 07:28