有什么方法可以从两个不同的字符串中提取/剪切一个公共字符串吗?

有什么方法可以从两个不同的字符串中提取/剪切一个公共字符串吗?

用于从 2 个部分相似、部分不同的字符串中提取公共字符串的 Bash 或 Linux 命令是什么

如何获取变量

a="How good is it to"

在......之外

b="How good is it to die in defending fatherland"
c="How good is it to live in dedicating oneself to nation"

答案1

对字符串进行 bash 循环:

i=0
a=
while [[ ${b:i:1} == ${c:i:1} ]]; do a+=${b[i]}; ((++i)); done

或者,通过较少的操作:

i=0
while [[ ${b:i:1} == ${c:i:1} ]]; do ((++i)); done
a=${b:0:i}

请注意,这将产生以下字符串:

printf -- '-->%s<--\n' "$a"
-->How good is it to <--

...带有尾随空格,因为该字符对于两个源字符串都是通用的。

答案2

尝试以下代码:

b="How good is it to die in defending fatherland"
c="How good is it to live in dedicating oneself to nation"
a=()
count=0
for i in ${b[@]}
do
        if [ "`echo "${c[@]}" | grep $i`" ]; then
                a[count]=$i
                count=$((count+1))
        fi
done
echo ${a[@]}

答案3

i have redirected value of variable  "a" and "b" to file "file1" and "file2"

Below is command i have used to fetch the common strings

如果有任何建议或更正,请告诉我

for i in {1..13}; do awk -v i="$i" 'NR==FNR{a[$i];next}($i in a){print $i}' file1 file2 ; done|sed '/^$/d'| perl -pne "s/\n/ /g"

输出

How good is it to in

相关内容