我的第一個檔案-
#cat 123
tom,123
jack,222
rock
google,908
mohan,323
ram,789
我的第二個檔案 -
#cat www
vicky,tom,home
google,monk,uber
dhoom,monk,uber
ram,monk,uber
rock,monk,uber
jack,monk,uber
所需的輸出 -
#cat match_output.txt
tom,123,vicky,tom,home
rock,rock,monk,uber
jack,222,jack,monk,uber
google,908,google,monk,uber
ram,789,ram,monk,uber
現在,我只得到這個 -
#cat match_output.txt
rock,monk,uber
My Script -
#!/bin/bash
# because File2 is bigger, it gets the main loop.
# read each line of File2
>/var/lib/jenkins/Jack/match_output.txt
while IFS=, read -r string; do
# read each line of File1.txt
while IFS=, read -r string2; do
# check match, and write if needed.
if [[ $string == *"$string2"* ]]; then
echo $string >> match_output.txt
echo "wrote "$string" to match_output.txt..."
fi
done < /var/lib/jenkins/Jack/123
done < /var/lib/jenkins/Jack/www
Not able to read 1st value of 1st file before the comma of each line and match with 2nd file line by line and print the output in a new file....
uj5u.com熱心網友回復:
要獲取逗號前的第一個值,可以使用cut命令。
使用以下代碼
if [[ $string == *"$string2"* ]]; then
echo $string >> match_output.txt
echo "wrote "$string" to match_output.txt..."
fi
你比較完整的行。如果您只想$string與 的第一個值(逗號之前)進行$string2比較,則需要調整此比較。
string2FirstValue=`echo "$string2" |cut -d',' -f1`
if [[ $string == *"$string2FirstValue"* ]]; then
echo $string2,$string >> match_output.txt
fi
uj5u.com熱心網友回復:
更安全,更有效的方法是使用awk:
awk '
BEGIN {FS=OFS=","}
FNR == NR {
map[$1] = $0
next
}
{
for (i=1; i<=NF; i)
if ($i in map) {
print map[$i], $0
next
}
}' 123 www
tom,123,vicky,tom,home
google,908,google,monk,uber
ram,789,ram,monk,uber
rock,rock,monk,uber
jack,222,jack,monk,uber
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/453322.html
標籤:linux bash loops while-loop
上一篇:函式回圈隨機停止
