所以我有两根绳子,它们有不同的尺寸
获取本地城市返回每个公民居住的城市的名称
获取当地护士返回每个护士工作的城市名称,前面有 CS。
GetLocalCit=$(awk -F "[:]" '{print $4}' citizens.txt)
GetLocalNurse=$(awk -F "[:]" '{print $3}' nurses.txt)
输出获取本地城市是:
Lisboa
Santarem
Porto
Porto
Lisboa
Braga
Braganca
Setubal
Setubal
Porto
Leiria
Santarem
Porto
Lisboa
输出获取当地护士是:
CSLisboa
CSPorto
CSSantarem
CSSetubal
CSLeiria
CSBraga
CSBraganca
CSBeja
CSEvora
CSFaro
CSCoina
CSMarvao
CSTrasOM
CSTrs
CSAA
CSAB
CSAC
CSAD
CSAE
CSAF
我想做的是比较每个不同的城市名称来自获取本地城市与每个城市名称获取当地护士如果我找到一个匹配项(也就是说,如果一个城市的名称已经在里面获取当地护士),然后我想附和“这个城市有一个护士”。
我在网上查了这个并尝试实现这个的变体
#!/bin/bash
STR='GNU/Linux is an operating system'
SUB='Linux'
if [[ "$STR" == *"$SUB"* ]]; then
echo "It's there."
fi
在我的代码中,但它可能不起作用,因为两个字符串中都有多个由 '\n' 分隔的单词...
我也想过创建一个尽管循环但不知道如何用字符串正确实现它!
答案1
我认为你最好使用grep
和获取本地城市作为搜索字符串列表:
grep -f GetLocalCit GetLocalNurse
或者如果它们是命令而不是文件
grep -f <(GetLocalCit) <(GetLocalNurse)
它将返回以下内容:
CSLisboa
CSPorto
CSSantarem
CSSetubal
CSLeiria
CSBraga
CSBraganca
然后你可以使用这个列表,例如通过 sed:
grep -f GetLocalCit GetLocalNurse | sed 's/CS/There is already a nurse in /'
最终得到:
There is already a nurse in Lisboa
There is already a nurse in Porto
There is already a nurse in Santarem
There is already a nurse in Setubal
There is already a nurse in Leiria
There is already a nurse in Braga
There is already a nurse in Braganca
请注意这如何取消重复城市获取本地城市
现在来看原始代码示例:
您需要循环这两个列表,我假设它们是这里的文件:
for city in $(cat GetLocalCit) ; do
for nurse in $(cat GetLocalNurse) ; do
if [[ $nurse =~ $city ]] ; then
echo "Nurse found in $city."
fi
done
done
使用嵌套循环可能不是很有效bash
。
Nurse found in Lisboa.
Nurse found in Santarem.
Nurse found in Porto.
Nurse found in Porto.
Nurse found in Lisboa.
Nurse found in Braga.
Nurse found in Braga.
Nurse found in Braganca.
Nurse found in Setubal.
Nurse found in Setubal.
Nurse found in Porto.
Nurse found in Leiria.
Nurse found in Santarem.
Nurse found in Porto.
Nurse found in Lisboa.
保留所有重复。
答案2
comm -12 <(GetLocalCit | sort -u) <(GetLocalNurse | cut -c3- | sort -u) |
sed -E 's/^/There is a nurse in /'
There is a nurse in Braga
There is a nurse in Braganca
There is a nurse in Leiria
There is a nurse in Lisboa
There is a nurse in Porto
There is a nurse in Santarem
There is a nurse in Setubal
这用于comm
识别一对已排序文件中的公共行