[英]Shell scripting UNIX
我們有一個包含幾個元素列表的文件,必須檢查每個元素是否存在於包含多個文件夾、子文件夾和文件的目錄中。 如果我們找到特定元素,我們應該將其填充到一個文件中,如果它不存在,則必須填充到另一個文件中...我們如何使用 unix shell 腳本來實現? 示例:file1: ABCD 如果我們在任何文件中找到元素 A/B/C/D,則應將其填充到名為“present.txt”的文件中,否則應填充到“Absent.txt”中。 提前致謝
這不是一個代碼編寫服務,但無事可做,我還是為你做了,但老實說,除非嘗試自己編寫,否則你不會學到很多東西。
您沒有說明元素文件中的每行是否有一個文件名,或者每行有幾個。 我的測試輸入文件 gash.txt 具有以下內容:
A B C D
E F G H
I J K L
如果每行一個,那么腳本會更簡單。 這里是:
#!/bin/sh
# Initialise filenames
elements=gash.txt
directory=gash
present=present.txt
absent=absent.txt
# Note that when these are used I enclose them in "quotes"
# This is to guard against embedded spaces in the names
# Zeroise files
> "$present"
> "$absent"
# If you have command-line arguments then save them here
# because I am about to blow them away with the 'set'
# 'read' reads each line into variable 'REPLY' by default
while read
do
# This 'set' trick will overwrite the program parameters
# It will NOT work if the names in $elements have embedded whitespace
set $REPLY
# This loops through the command-line arguments by default
for fname
do
# if you don't know the 'find' command then look at 'man find'
# Note that 'find' returns 0 even if it didn't find the file
result=$(find "$directory" -name "$fname")
# The '-n' test returns true if $result is not empty
if [[ -n $result ]]
then
echo "$fname found"
echo "$fname" >> "$present"
else
echo "$fname not found"
echo "$fname" >> "$absent"
fi
done
done < "$elements"
一個更復雜的版本會從文件名構建一個模式,並只使用一次“查找”調用來進行搜索,但生命太短暫了(也許是以后的好項目)。
隨意問的問題!
你也可以這樣做:
文件 1 包含:
A
B
C
D
代碼 :
directory="your path"
cat file1 | while read line
do
res=$(find $directory -name "$line")
if [[ -n $res ]]
then
echo $line >> present.txt
else
echo $line >> absent.txt
fi
done
此致
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.