我需要按 ISBN 号(第三列)将列表从输入文件排序到 afile.sh
并发送到输出文件 ( file.out
)。输入文件 ( file.input
) 将有一个列表
Donald Smith,Fire Lands,97868545414459
Adam Barry,The Armies,97564325678855
Jennifer Lelan,Childhood dreams,97546766544237
Run Code Online (Sandbox Code Playgroud)
使用循环结构来处理数据和标题Author
Name of book
ISBN
。
结果
Author Name of Book ISBN
Jennifer Lelan Chilhood Dreams 97546766544237
Adam Barry The Armies 97564325678855
Donald Smith Fire Lands 97868545414459
Run Code Online (Sandbox Code Playgroud)
首先,您不会遍历这些数据:为什么使用 shell 循环来处理文本被认为是不好的做法?
如果文件中唯一的逗号是分隔字段的逗号,则
sort -t ',' -k3n -o file.output file.input
Run Code Online (Sandbox Code Playgroud)
将根据第三列中的数字对数据进行数字排序。输出将写入file.output
.
对于给定的数据,file.output
看起来像
Jennifer Lelan,Childhood dreams,97546766544237
Adam Barry,The Armies,97564325678855
Donald Smith,Fire Lands,97868545414459
Run Code Online (Sandbox Code Playgroud)
为了进一步处理这些数据,可以考虑使用一个awk
程序。由于您尚未指定要进行的处理类型,因此以下只是将数据提取到每一行的变量中(不是真正必需的)并打印它们:
sort -t ',' -k3n file.input |
awk -F ',' '{ author=$1; title=$2; isbn=$3;
printf("Author: %s\nTitle: %s\nISBN: %s\n",
author, title, isbn) }'
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,无需将排序后的数据存储在中间文件中。
给出问题中的数据的输出:
Author: Jennifer Lelan
Title: Childhood dreams
ISBN: 97546766544237
Author: Adam Barry
Title: The Armies
ISBN: 97564325678855
Author: Donald Smith
Title: Fire Lands
ISBN: 97868545414459
Run Code Online (Sandbox Code Playgroud)
要将数据放入美观的列中,并在 ISBN 号中使用破折号,您不需要awk
. 以下sed
用于 ISBN 编号的column
格式设置和列的格式设置:
sort -t ',' -k3n file.input |
sed -E -e 's/,([0-9]{3})([0-9]{4})([0-9]{5})/,\1-\2-\3-/' |
column -s ',' -t
Run Code Online (Sandbox Code Playgroud)
输出将是
Jennifer Lelan Childhood dreams 975-4676-65442-37
Adam Barry The Armies 975-6432-56788-55
Donald Smith Fire Lands 978-6854-54144-59
Run Code Online (Sandbox Code Playgroud)
请注意,ISBN 数字看起来有点不稳定。那是因为它们的长度为 14 位。 真正的ISBN 号是 10 位或 13 位长,上面的代码假设它们是 13 位(或至少 12 位)。
添加列标题:
sort -t ',' -k3n file.input |
{ echo 'Author,Name of book,ISBN'
sed -E -e 's/,([0-9]{3})([0-9]{4})([0-9]{5})/,\1-\2-\3-/'
} |
column -s ',' -t
Run Code Online (Sandbox Code Playgroud)
其中产生
Author Name of book ISBN
Jennifer Lelan Childhood dreams 975-4676-65442-37
Adam Barry The Armies 975-6432-56788-55
Donald Smith Fire Lands 978-6854-54144-59
Run Code Online (Sandbox Code Playgroud)
...在 shell 中不使用显式循环。
归档时间: |
|
查看次数: |
77 次 |
最近记录: |