簡體   English   中英

Bash 腳本在數據庫中搜索名稱

[英]Bash script to search for a name in a database

我有一個包含多個.txt文件的數據庫,我需要在所有這些txt中自動搜索特定名稱。

終端中,我通常執行grep word:otherword /path/to/file/text1.txt並獲得所有結果的列表。

我怎樣才能自動化所有,以便腳本問我“插入單詞”然后插入其他單詞”,然后它搜索所有文件給我一個干凈的結果“單詞其他單詞”

編輯1:

目前的代碼

#!/bin/bash

    read -p "Insert Word: " insertWord
    read -p "Insert OtherWord: " insertOtherWord
    printf "Executing grep ${insertWord}:${insertOtherWord} $(find path/to/file/name.txt -name '*.txt')"
    grep "${insertWord}:${insertOtherWord}" $(find path/to/file/name.txt -name '*.txt')

編輯2:

#!/bin/bash

read -p "word3: " word3
read -p "word4: " word4
read -p "word1: " word1
read -p "word2: " word2
printf "Searching for ${word1}:${word2}:${word3}:${word4} $(find path/to/file -name '*.txt')"
grep -i -w "${word1}:${word2}:${word3}:${word4}" $(find path/to/file -name '*.txt') | cut -d":" -f2-

鑒於更新的腳本EDIT2並鑒於word2是一組可變長度數字,是否有一種方法可以:

  1. 搜索,或者搜索word1或兩個或所有這些
  2. word2不是必需的,但如果我不添加它,則搜索不會運行; 試圖添加通配符 * 但它給了我一個錯誤

Output 示例為:

word1:numbervariablelenght:word3:word4

這個..

#!/bin/bash

read -p "Insert Word : " insertWrod
read -p "Insert OtherWord : " insertOtherWord
printf "Executing grep ${insertWrod}:${insertOtherWord} $(find . -name '*.txt')"
grep "${insertWord}:${insertOtherWord}" $(find . -name '*.txt')

PS - 根據需要將選項調整為 grep

編輯

您可以替換命令中的路徑,如果您想避免來自 output 行的路徑,格式為path/to/file/file.txt:word:otherword ,您可以進行cut ,例如

#!/bin/bash

read -p "Insert Word : " insertWrod
read -p "Insert OtherWord : " insertOtherWord
read -p "Path : " somePath

# Make Sure Path exists and its a directory
if [ -d "$somePath" ] then
    grep "${insertWord}:${insertOtherWord}" $(find $somePath -name '*.cpp') | cut -d":" -f2- 
fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM