在单个命令中将awk的输出管道输出到sed

时间:2014-06-03 19:36:38

标签: awk sed

我有一个简单的文件,如:

a 123
b 234

在第二个文件中,我想用对应于 - >的值替换字符串。 " 123" 在一个命令中

有没有办法将grep "a" file1 | awk {print $2}的结果传递给sed s/string/my_output/g file2

4 个答案:

答案 0 :(得分:1)

这是awk

cat file1
a 123
b 234

cat file2
cat
bad hat

awk -v FS="" 'FNR==NR {split($0,b," ");a[b[1]]=b[2];next} {for (i=1;i<=NF;i++) $i=a[$i]?a[$i]:$i}1' file1 file2
c 123 t
234 123 d   h 123 t

它是如何运作的。

awk -v FS="" '                      # By setting Field Separator to nothing, it works on one and one letter
FNR==NR {                           # This is true only for the first file (file1)
    split($0,arr-b," ")             # Split the data in first file (arr-b[1]=first filed, eks a, arr-b[2]=second field, eks 123
    arr-a[arr-b[1]]=arr-b[2]        # Store this to an array using field 1 as index. arr-a[a]=123 arr-a[b]=234 etc
    next}                           # Skip to next record in file1
    {                               # Run this for file2
    for (i=1;i<=NF;i++)             # Loop trough on by on letter "c" "a" "t"
        $i=arr-a[$i]?arr-a[$i]:$i}  # Test the letter one by one if its found in array "arr-a", if so use data from array, if not keep value
1                                   # Since this always will be true, do default action "print $0" (print every line)
' file1 file2                       # Read file1 and file2

答案 1 :(得分:0)

如果我正确解释您的问题,请尝试

sed 's@^\(.*\) \(.*\)$@s/\1/\2/g@' SimpleFile > substitutions.file
sed -f substitutions.file 2ndFile > 2ndFile.tmp && mv 2ndFile.tmp 2ndFile

第一步将创建一个像

这样的sed子文件
s/a/123/g
s/b/234/g

当在上面的第2行中使用时,将用123等替换每个a

IHTH

答案 2 :(得分:0)

您可以执行以下操作:

grep a file1| awk '{print $2}' > tmp.txt

这会将'123'放入临时文件中。然后:

sed -f script.sed file2

script.sed的内容是

/string to replace/ {
    r tmp.txt
    d
}

此脚本将“要替换的字符串”替换为tmp.txt的内容。

答案 3 :(得分:0)

这是一个纯粹的Awk解决方案。将字典放在'adict.dat'中,然后将输入文件传递给Awk命令

BEGIN { 
    while(( getline line < "adict.dat" ) > 0 ) {
        $0 = line;
        myvars[$1] = $2;
    }
}

{
    for (varname in myvars) {
        gsub(varname, myvars[varname]);
    }
    print;
}

运行示例

/bin/echo 'a x b y' | gawk -f arepl.awk 

输出

123 x 234 y