我正在撰寫一個 bash 腳本,以通用格式執行各種操作。最初,腳本首先宣告一個設定為檔案內容的變數,我們可以稱之為“file1.txt”。
file1.txt 將只包含 1 行,其中 1 行將只有一個整數。預測整數是什么是不可能的。此外,一旦將變數設定為該整數,重新讀取 file1.txt 以希望將變數重新設定為相同的整數是不可靠的。因此,我們必須將整數概括為腳本中的變數。
此外,還有另一個檔案,我們稱之為“file2.txt”,它有很多行,每一行都有一個唯一的整數。保證該檔案的 1 行和只有 1 行將具有我們為變數設定的相同整數。
僅使用設定為該整數的變數,可以使用 what 命令從“file2.txt”中洗掉包含所需整數的行。
我曾嘗試使用命令 sed 和 auk,但是我在將變數用作字串時遇到了麻煩。
file1.txt 的示例:
123
file2.txt 的示例:
456
86454768
35434586745
1231
123
12323
123123
目標是洗掉與 file2.txt 中“123”完全匹配的行,或者在這種情況下是 file2.txt 中的第 5 行。
我目前的代碼:
#This is the only time we can read this file to set the variable
Number="$(cat ./file1.txt)"
#Now we need to remove whatever number $Number is from file2.txt
(unknown command here)
我已經嘗試過 awk 和 sed,但無濟于事。我可能錯誤地使用了語法。以下是失敗命令的示例:
- awk '$0 != $Number' < ./file2.txt
- awk [ $0 != $Number ] < ./file2.txt
- sed -i '/^$Number$/d' ./file2.txt
- sed -i '/^"$Number"$/d' ./file2.txt
- sed -i '/^(($Number))$/d' ./file2.txt
任何幫助將不勝感激!
uj5u.com熱心網友回復:
$ awk 'NR==FNR{a[$0]; next} !($0 in a)' file1.txt file2.txt
456
86454768
35434586745
1231
12323
123123
或者如果您在變數中有目標值number:
grep -vFx "$number" file2.txt
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341772.html
