简体   繁体   English

sed | 脚本中的grep怪异行为

[英]sed | grep weird behaviour in script

THE ISSUE 问题

I have two files, 我有两个档案

File1 文件1

INT1;INT2;INT3 INT1; INT2; INT3
INT4;INT5;INT6 INT4; INT5; INT6
INT7;INT7;INT9 INT7; INT7; INT9

File2 文件2

INT1;INT2;INT3 INT1; INT2; INT3

Next I'll grep the difference between the files and only take the integers of third column. 接下来,我将grep文件之间的差异,并且仅采用第三列的整数。

  DIFFERENCE=`grep -vxFf File1 File2 | awk 'BEGIN { FS = ";" } ; { print $3 }'`

resulting in 导致

INT6 INT9 INT6 INT9

Next I want to substitute the spaces with line breaks 接下来,我想用换行符代替空格

echo $DIFFERENCE | sed 's/ /;\n/g'

which results in 导致

INT6; INT6;
INT9 INT9

Just as it should. 正如它应该的那样。

Instead, when I do it in the script, it returns 相反,当我在脚本中执行此操作时,它将返回

INT6 INT6
INT9 INT9



Why does it do this in script, and is there solution to this / how can I modify my result easily? 为什么要在脚本中执行此操作,并且有解决方案?如何轻松修改结果?



ORIGINAL CODE - FOR CLARIFICATION 原始代码-澄清

Original code and output here 原始代码并在此处输出

     CODE=`grep -vxFf $FOUND $COMPARETO | awk 'BEGIN { FS = ";" } ; { print $3 }'` 
     echo "$CODE;" | sed 's/ /;\n/g' > "testfile"   

8000070118157 8000070118157
8002820000804 8002820000804
3394700015011; 3394700015011;

Your intermediate output is not INT6 INT9 on single line but already two lines, therefore sed doesn't replace anything. 您的中间输出不是INT6 INT9上的INT6 INT9 ,而是两行,因此sed不会替换任何内容。

You can do all of this in awk itself, for example 例如,您可以在awk本身中完成所有这些操作

$ awk -F';' 'NR==FNR{a[$0];next} !($0 in a){print $3 FS}' file2 file1
INT6;
INT9;

if you don't want the last ; 如果你不想最后一个; , perhaps easier to pipe to sed '$ s/;$//' ,也许更容易用管道传递sed '$ s/;$//'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM