【问题标题】:How to compare two files and replace of another file content on position of first file?如何比较两个文件并在第一个文件的位置替换另一个文件内容?
【发布时间】:2020-06-29 15:52:53
【问题描述】:

如果找到匹配并且位置明智,我想替换另一个文件的一些文本。

第一个文件:

abc ram
bdc jay 
vlm rock

第二个文件:

grep -f -w '' /d/demo.txt  
grep -f -w '' /d/demo.txt 
grep -f -w '' /d/demo.txt 

如您所见,第一个文件数为 3,第二个文件数为 3。我的输出应该是这样的:

grep -f -w 'abc ram' /d/demo.txt  
grep -f -w 'bdc jay' /d/demo.txt 
grep -f -w 'vlm rock' /d/demo.txt 

第一个文件值的位置应该放在第二个文件的第一个位置,依此类推。

abc ram

grep -f -w 'abc ram' /d/demo.txt 

我已经编写了一些代码,但无法构建逻辑.. 最多匹配两个文件计数是在逻辑无法执行的内部完成的。

if [ $count_firstfile == $count_secondfile ]
then 
      // Logic needed here 
      
elif [ $count_firstfile != $count_secondfile ]    
then 

else 
    echo "Nothing to do"
fi  

【问题讨论】:

  • 请注意,[ $anything == $anything_else ] 存在错误的原因有很多。使用[ "$anything" = "$anything_else" ],引用每个变量,并且只使用一个= 而不是==。 (包括 bash 在内的一些 shell 包含一个允许使用 ==test 的实现,但是让代码只在 bash 而不是像 dash 或 ash 这样的基线 POSIX shell 上工作不是好的做法;省略引号引入各种各样的错误,具体取决于运行时使用的值)。
  • 看起来你是writing a script to generate another script。不如我们帮你去掉中间人,让第一个脚本直接运行grep 调用?

标签: linux shell


【解决方案1】:

您需要的一般做法在Read from two files line by line and process them simultaneously 中给出。

#!/usr/bin/env bash
case $BASH_VERSION in '') echo "This script requires bash" >&2; exit 1;; esac

sigil="''"
while IFS= read -r command_line <&3 && IFS= read -r arg_line <&4; do
  [[ $command_line = *"$sigil"* ]] || { echo "ERROR: No sigil in $command_line" >&2; exit 1; }
  printf -v arg_line_q '%q' "$arg_line"
  printf '%s\n' "${command_line//$sigil/$arg_line_q}"
done 3<file_with_commands 4<file_with_arguments >combined_output_file

这从file_with_commandsfile_with_arguments 读取,并写入combined_output_file。请注意,在 bash 5 中,您可以使用 ${arg_line@Q} 来避免需要 printf -v arg_line_q %q "$arg_line" 行。

【讨论】:

  • ...你能详细解释上面的代码无法理解发生了什么......我如何将文件传递给上面的脚本
  • ……你能详细解释一下上面的代码吗?无法理解发生了什么……我如何将文件传递给上面的脚本
【解决方案2】:

抛开代码逻辑,下面的命令应该会产生预期的结果:

grep -Ff First_file /d/demo.txt

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 2014-05-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多