gpt4 book ai didi

bash - Unix bash 切割和 grep

转载 作者:行者123 更新时间:2023-11-29 09:01:36 25 4
gpt4 key购买 nike

我有一个名为 db.txt 的文本文件。文件中的一些示例行如下:

Harry Potter and the Sorcerer's Stone:J.K. Rowling:21.95:100:200

Harry Potter and the Chamber of Secrets:J.K. Rowling:21.95:150:300

Lord of the Rings, The Fellowship of the Ring:J.R.R. Tolkien:32.00:500:500

A Game of Thrones:George R.R. Martin:44.50:300:250

然后在我的脚本中,我有以下几行:

echo "Enter title:"
read TITLE

cut -d ":" -f 1 db.txt | grep -iw "$TITLE" | while read LINE
do
STRING="`echo $LINE | cut -d ":" -f 1`,"
STRING="$STRING `echo $LINE | cut -d ":" -f 2`, "
STRING=" \$$STRING`echo $LINE | cut -d ":" -f 3`,"
STRING=" $STRING`echo $LINE | cut -d ":" -f 4`,"
STRING=" $STRING`echo $LINE | cut -d ":" -f 5`"
done

有没有办法从 cut 中 grep 一个特定的字段,然后将整行传递给 while 循环?

例如,如果我输入“Harry Potter”,它应该显示:

Harry Potter and the Sorcerer's Stone, J.K. Rowling, $21.95, 100, 200

Harry Potter and the Chamber of Secrets, J.K. Rowling, $21.95, 150, 300

最佳答案

如果您可以使用 bash 的正则表达式匹配(或者可以改用 shell 模式匹配),那么您可以在没有 cut 和没有 grep 的情况下执行此操作。

我们的想法是逐行读取文件,然后将行拆分为一个数组。完成后,进行所需的比较和输出。

这是该技术的演示:

#! /bin/bash
echo "Title:"
read title

# shopt -s nocasematch # if you want case-insensitive matching

while read line ; do # this read takes data from input.txt, see
# end of loop
IFS=: read -a parts <<< "$line" # this splits the line on ":" into
# an array called parts

if [[ ${parts[0]} =~ $title ]] ; then # regex matching
printf "%s -- %s\n" "${parts[1]}" "${parts[2]}"
fi
done < input.txt

关于bash - Unix bash 切割和 grep,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14237043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com