Text-Processing

在文件中搜尋模式 grep

  • June 1, 2022

我有diff以下格式的輸出:

$ curr_dt=$(date +%m_%d_%Y)
$ echo $curr_dt
$ diff -q /POC/$curr_dt/DDL/ /POC/Backup/DDL/
Only in /POC/Backup/DDL/: comp1.txt
Only in /POC/Backup/DDL/: comp.txt
Only in /POC/Backup/DDL/: junk.txt
Files /POC/$curr_dt/DDL/test.demo_table1.txt and /POC/Backup/DDL/test.demo_table1.txt differ
Only in /POC/$curr_dt/DDL/: test.demo_table2.txt

我現在想從上面顯示的數據中得到以下資訊:

  1. 僅在 /POC/Backup/DDL/ 中:
  2. 僅在 /POC/$curr_dt/DDL/ 中:
  3. 文件 * 不同

例如:

diff -q /POC/05_26_2022/DDL/ /POC/Backup/DDL/ | grep -i '^Files.*.differ$'
Files /POC/05_26_2022/DDL/test.demo_table1.txt and /POC/Backup/DDL/test.demo_table1.txt differ

像上面一樣,我得到了一整行數據。我只需要從中獲取 test.demo_table1.txt 並將其保存在文件中。同樣地


i am not able to grep with variable $curr_dt in the file

看起來您的$curr_dt變數未在上面給出的程式碼段中設置/未擴展。至少它不會echo也不會出現在diff’s 的輸出中。-x使用(xtrace) 選項集執行您的程式碼。對於您的其他問題,請嘗試

awk '/^Only/ {gsub("[/:]+", "_", $3); print $NF > $3} /^Files.*differ/ {sub(/^.*\//, "", $2); print $2 > "different"}' file

它應該創建三個文件,其中包含各自的文件名。

根據 OP 的反复要求,文件名減少為已辨識 / 辨識目錄:

awk '
/Only/          {m = split($3, T, "[/:]+")
                print $NF > T[m-2]
               }
/Files.*differ/ {sub(/^.*\//, "", $2)
                print $2 > "different"
               }
' file

引用自:https://unix.stackexchange.com/questions/703962