加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Unix bash切割和grep

发布时间:2020-12-15 22:52:14 所属栏目:安全 来源:网络整理
导读:我有一个名为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.
我有一个名为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

有没有办法从剪切中获取特定字段然后将整行传递到while循环?

例如,如果我进入“哈利波特”,
它应该显示:

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

Harry Potter and the Chamber of Secrets,150,300

解决方法

如果你没有使用bash的正则表达式匹配(或者可以使用shell模式匹配),你可以不剪切而没有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 -- %sn" "${parts[1]}" "${parts[2]}"
        fi
done < input.txt

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读