我有两个文件。 文件A
有一个单词列表,每行一个。 文件B
包含另一个巨大的单词列表,但有些很长。 我如何使用sed或awk从文件A
取出每一行,并将它与文件B
中不长于6个字符的每一行相结合? 理想情况下,将所有结果吐出一个新文件。
例如:
文件A:
cool beans sad
文件B:
armadillo snake bread
新文件:
coolsnake coolbread beanssnake beanbread sadsnake sadbread
不一样的顺序,你的输出,但可能是有用的:
awk ' FNR == NR { words[ $1 ] = 1; next } FNR < NR { if ( length( $1 ) <= 6 ) for ( word in words ) { print word $0 } } ' fileA fileB
输出:
coolsnake sadsnake beanssnake coolbread sadbread beansbread
#!/bin/bash while read line1; do while read line2;do [[ $(echo $line2 | wc -c) -lt 7 ]] && \ echo $line1$line2 done < './B.txt' done < './A.txt'
这样的事情,只适合自己它给了我:
coolsnake coolbread beanssnake beansbread sadsnake sadbread
这可能适合你:
sed 's|.*|sed "/......./d;s/.*/&\&/" fileB|' fileA | sh
用GNU sed:
sed 's|.*|sed "/......./d;s/.*/&\&/" fileB|e' fileA
一种使用perl
:
script.pl
内容:
use warnings; use strict; die qq[Usage: perl $0 <fileA> <fileB>\n] unless @ARGV == 2; open my $fh, q[<], pop or die $!; my @words = map { chomp; $_ } grep { length( $_ ) <= 6 } <$fh>; while ( <> ) { chomp; for my $word ( @words ) { printf qq[%s\n], $_ . $word; } }
像这样运行它:
perl script.pl fileA fileB
以下输出:
coolsnake coolbread beanssnake beansbread sadsnake sadbread
与bash:
mapfile -t shortwords < <(sed -r 's/.{7,}/d' B.txt) while read word; do for suffix in "${shortwords[@]}"; do echo "$word$suffix" done done < A.txt