Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 识别在Bash中连续重复单词的行_Regex_String_Bash - Fatal编程技术网

Regex 识别在Bash中连续重复单词的行

Regex 识别在Bash中连续重复单词的行,regex,string,bash,Regex,String,Bash,假设我有以下文件: one two three two three four three four four three four five 我如何确定哪一行有一个连续重复的单词?我正在尝试获得如下输出: 3:four:three four four 首先是行号,然后是单词,然后是单词出现的行 这就是我到目前为止所做的: while read line do echo $line > file sed -e 's/ /\'$'\n/g' file | sort | uniq

假设我有以下文件:

one two three
two three four
three four four
three four five
我如何确定哪一行有一个连续重复的单词?我正在尝试获得如下输出:

3:four:three four four
首先是行号,然后是单词,然后是单词出现的行

这就是我到目前为止所做的:

while read line
do
   echo $line > file
   sed -e 's/ /\'$'\n/g' file | sort | uniq -c | sort -nr | head -1
done < $1
我在考虑把你的成果传给别人

head-1


对于以频率和单词为参数的自定义脚本,必须有一种更简单的方法来实现这一点。

除了打印行号外,这可以:

sed -n -r '/\b([^ ]+) \1\b/s/^.*\b([^ ]+) \1\b/\1:&/p' 

如果Perl解决方案可以,那么这可能会有所帮助:

perl -lne '/\b(\w+) \1\b/ && print join ":",$.,$1,$_;' file

您可以尝试以下方法:

cat -n stack | sed -n -r '/\b([^ ]+) \1\b/s/^.*\b([^ ]+) \1\b/\1:&/p' | sed 's/     / /' | awk '{ i = $1; $1 = $2":"; $2 = i; print; }'
使用cat-n对行进行编号,然后使用Barmar的sed命令。之后,删除所有多余的空格,切换第1列和第2列的值并打印出来。尽可能接近它:

 3: four: three four four

使用
awk

awk '{for(i=1;i<=NF;i++)if($i==$(i+1)){print NR,$i,$0 }}' OFS=':' file

awk'{for(i=1;i您可以使用带有正则表达式匹配的BASH循环来实现这一点

n=1
while read -a line; do
    for i in ${line[@]}; do
        if [[ ${line[@]} =~ ($i).*($i) ]]; then
            echo "${n}:${i}:${line[@]}"
            break
        fi
    done
    ((n++))
done < $1
n=1
读一行的时候;做一件事
对于${line[@]};do中的i
如果[${line[@]}=~($i)。*($i)];则
回显“${n}:${i}:${line[@]}”
打破
fi
完成
((n++)
已完成<$1

wow@Guru您能解释一下
print join
后的部分
$
代表什么吗?@aelor它们是
perl
特殊变量。
$。
保留行号,
$1
具有捕获的反向引用(在本例中为单词)而
$
保存整行。由于行不是由
分隔的,
join
帮助打印由
分隔的所有内容。
$ awk '{for(i=1;i<=NF;i++)if($i==$(i+1)){print NR,$i,$0 }}' OFS=':' file
3:four:three four four
n=1
while read -a line; do
    for i in ${line[@]}; do
        if [[ ${line[@]} =~ ($i).*($i) ]]; then
            echo "${n}:${i}:${line[@]}"
            break
        fi
    done
    ((n++))
done < $1