从另一个文件中grep一个文件只能以一种方式工作.为什么? [英] grep a file out of another file works only one way. Why?

查看:56
本文介绍了从另一个文件中grep一个文件只能以一种方式工作.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下脚本.它检查两个环境,以查看两者是否具有相等的环境变量名称集.问题开始于第二个grep行.如果文件 Ds1 Ps1 相同,则完全不会生成 Du .但是,第一个grep会生成一个空的 Pu 文件.

Please, consider the script below. It checks two environments to see if both have equal sets of env variables names. The problem starts on the line of second grep. If files Ds1 and Ps1 are the same, Du is not produced at all. The first grep however produces an empty Pu file.

另一个奇怪的事情.如果我使用 ./script 运行脚本,则会出现问题,如果我使用 bash脚本,则两个grep行的行为相同,将产生两个空文件.

Another strange thing. If I run the script with ./script the problem occurs, if I use bash script, both grep lines behave identically producing two empty files.

有什么解释吗?无论调用方法如何,如何使它们以相同的方式运行?

Any explanation? How can I make them run the same way regardless of invocation method?

#!/bin/bash -e

# Script name, added to console prints 
action="\e[32m"${0}"\e[39m"

exit_code=0

echo -e ${action}": Start of script."
echo

#get var names from both files
awk '{print $1}' Ds > Ds1
awk '{print $1}' Ps > Ps1

# Get vars not in Dev
grep -Fxvf Ds1 Ps1 > Pu
# Get vars not in Prod
grep -Fxvf Ps1 Ds1 > Du

# If there are vars unique to Dev, print them
if [ -s Du ]; then
  echo -e ${action}": List of env variables unique to Dev:"
  echo

  while read p; do
    cat Ds | grep $p
  done < Du
  echo
  exit_code=1
fi

# If there are vars unique to Prod, print them
if [ -s Pu ]; then
echo -e ${action}": List of env variables unique to Prod:"

  while read line; do
     cat Ps | grep $line
  done < Pu
  exit_code=1
fi

exit ${exit_code}

如果需要,此处是 Ds1 文件的一部分:

Here is a part of Ds1 file if needed:

AMBURAPP_ACCESS_TOKEN
AWS_ACCESS_KEY_ID
AWS_DB_BACKUP_REGION
AWS_DB_BACKUP_S3_BUCKET_NAME
AWS_SECRET_ACCESS_KEY
AWS_USER_NAME
BUNDLE_WITHOUT
DB_ENDPOINT
DB_NAME
DB_PASSWORD
DB_PORT
DB_USER
DEVISE_SECRET_KEY
DOMAIN
INTERCOM_API_KEY
MANDRILL_SUBACCOUNT
MANDRILL_USERNAME
PARAM5

运行 diff Ds1 Ps1 不会返回任何内容,即diff将两个文件视为相同的AFAIK.

running diff Ds1 Ps1 returns nothing, i.e. diff considers both files identical AFAIK.

我的问题是关于两个完全相同的结果的不同结果,而不是关于文件快速比较的方式.

My question is about different outcome of two identical greps and NOT about ways of fast comparison of files.

推荐答案

使用 -e 运行脚本会使脚本在命令失败时(例如 grep 失败)中止.没有匹配.

Running the script with -e causes it to abort when a command fails, such as when grep does not produce a match.

解决方法是显式处理所有可能的错误.要忽略错误,您可以使用类似的

The fix is to explicitly handle every possible error. To ignore an error, you can use something like

grep foo bar || true

这篇关于从另一个文件中grep一个文件只能以一种方式工作.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆