[英]Bash Comparing strings in a directory
您好我正在嘗試比較目錄中的兩個字符串。 格式如下。
{sametext}difference{sametext}
。
注意:{sametext} 不是每個文件的 static
例如
myfile_1_exercise.txt
與myfile_2_exercise.txt
相比
你能告訴我如何在 if 語句中匹配上述字符串。
基本上我需要知道如何忽略兩個字符串中的數字,以便它們相同。
一些示例代碼如下所示:
我的示例代碼如下所示:
for g in `ls -d */`;
do
if [ -d $g ]; then
cd $g # down 1 directories
for h in `ls *root`;
do
printf "${Process[${count}]} = ${basedir}/${f}${g}${h}\n"
h1=${h}
if [ "${h1}" = "${h2}" ]; then # NEED to MATCH SOME HOW??????????
echo we have a match
fi
h2=${h1}
let count+=1
done
cd ../
#printf "\n\n\n\n"
fi
done
應該用什么測試來確定這個而不是"${h1}" = "${h2}"
?
干杯,
麥克風
sed
在這里派上用場。
這基本上遍歷目錄中的每個文件,從文件名中提取兩個字符串,並保留其所有唯一組合的列表。
然后,它遍歷這個列表,並使用 bash 的通配符擴展來允許您遍歷每個集合。
編輯:擺脫了一個丑陋的黑客。
i=0
for f in *_*_*.txt
do
a=`echo "$f" | sed 's/\(.*\)_.*_\(.*\).txt/\1/g'`
b=`echo "$f" | sed 's/\(.*\)_.*_\(.*\).txt/\2/g'`
tmp=${all[@]}
expr match "$tmp" ".*$a:$b.*" >/dev/null
if [ "$?" == "1" ]
then
all[i]="$a:$b"
let i+=1
fi
done
for f in ${all[@]}
do
a=`echo "$f" | sed 's/\(.*\):\(.*\)/\1/g'`
b=`echo "$f" | sed 's/\(.*\):\(.*\)/\2/g'`
echo $a - $b
for f2 in $a_*_$b.txt
do
echo " $f2"
# ...
done
done
當然,這假設您關心的所有文件都遵循*_*_*.txt
模式。
"myfile_1_exercise.txt" == "myfile_2_exercise.txt"
你的意思是上面的測試應該返回true
(忽略數字)對嗎?
這就是我會做的:
h1="myfile_1_exercise.txt"
h2="myfile_2_exercise.txt"
if [ $( echo ${h1} | sed 's/[0-9]*//g' ) == $( echo ${h2} | sed 's/[0-9]*//g' ) ] ; then
# do something here.
fi
免責聲明:
也就是說,這是一個根據您的要求比較兩個字符串的腳本。 我相信你可以弄清楚如何在你的目錄列表腳本中使用它(你可能想順便考慮一下find
)
該腳本需要兩個字符串並打印匹配! 如果他們匹配
$ bash compare.sh myfile_1_exercise.txt myfile_2_exercise.txt
match!
$ bash compare.sh myfile_1_exercise.txt otherfile_2_exercise.txt
$
劇本:
#!/bin/bash
fname1=$1
fname2=$2
findStartMatch() {
match=""
rest1=$1 ;
rest2=$2 ;
char1=""
char2=""
while [[ "$rest1" != "" && "$rest2" != "" && "$char1" == "$char2" ]] ; do
char1=$(echo $rest1 | sed 's/\(.\).*/\1/');
rest1=$(echo $rest1 | sed 's/.\(.*\)/\1/') ;
char2=$(echo $rest2 | sed 's/\(.\).*/\1/');
rest2=$(echo $rest2 | sed 's/.\(.*\)/\1/') ;
if [[ "$char1" == "$char2" ]] ; then
match="${match}${char1}"
fi
done
}
findEndMatch() {
match=""
rest1=$1 ;
rest2=$2 ;
char1=""
char2=""
while [[ "$rest1" != "" && "$rest2" != "" && "$char1" == "$char2" ]] ; do
char1=$(echo $rest1 | sed 's/.*\(.\)/\1/');
rest1=$(echo $rest1 | sed 's/\(.*\)./\1/') ;
char2=$(echo $rest2 | sed 's/.*\(.\)/\1/');
rest2=$(echo $rest2 | sed 's/\(.*\)./\1/') ;
if [[ "$char1" == "$char2" ]] ; then
match="${char1}${match}"
fi
done
}
findStartMatch $fname1 $fname2
startMatch=$match
findEndMatch $fname1 $fname2
endMatch=$match
if [[ "$startMatch" != "" && "$endMatch" != "" ]] ; then
echo "match!"
fi
如果您實際上是在比較您提到的兩個文件...也許您可以使用diff
命令,例如
diff myfile_1_exercise.txt myfile_2_exercise.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.