从 Bash 中的文件中读取行并将单词解析为 mailx 参数的变量
我有一个 bash 脚本,它从 4 列(无标题)的文本文件中读取行。行数最多可以为 4 行或更少。每行中的单词由空格字符分隔。
[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 解决方案来解决下面提到的逻辑。
- 读取 $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 行到达
awk 或 sed 是否为上述迭代/提供了一个优雅的解决方案循环逻辑?
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
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.
- 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
Do awk or sed provide an elegant solution to the above iterating/looping logic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下:
head -n 4
从文本文件中读取最多四行。read
可以从一行读取多个变量,因此我们可以使用命名变量来提高可读性。<<<
可能是您想要的重定向,而不是<
。大概。Give this a shot:
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.如果您对如何显示文件中的文本行有很多控制,上面的 while 循环可以很好地作为 sed 和 awk 的简单替代方案。 read 命令也可以使用 -d 标志来使用指定的分隔符。
另一个简单的例子:
我使用 mysql 来获取用户和主机的列表,将其放入文件 /tmp/userlist 中,其文本如下所示:
我将这些变量传递到 mysql 命令中以获取这些用户和主机的授权信息并附加到/tmp/grantlist:
The above while loop works well as a simple alternative to sed and awk if you have a lot of control over how to display the lines of text in a file. the read command can use a specified delimiter as well, using the -d flag.
Another simple example:
I had used mysql to grab a list of users and hosts, putting it into a file /tmp/userlist with text as shown:
I passed these variables into a mysql command to get grant info for these users and hosts and append to /tmp/grantlist: