在bash脚本中管道到egrep并保存到变量

时间:2017-10-22 17:39:48

标签: bash

我是bash脚本的新手,并且我正在尝试编写一个bash脚本的一些问题。请参阅此代码段:

#!/bin/bash                                                                    
year=`date +'%Y'`                                                                                                                                     
holidaysXML=$(curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET \http://www.spiketime.de/feiertagapi/feiertage/$year | xmllint --format -)                                                
echo "$holidaysXML" | egrep "[0-9]{4}-[0-9]{2}-[0-9]{2}|>RP<"

在这种形式中,echo所打印的内容与预期的一样,但是当我尝试将结果安全地保存到变量端回显变量时,似乎没有执行egrep-part或者根本没有执行任何操作。

在阅读了其他一些主题之后,我已经尝试了以下内容:

test=$( "$holidaysXML" | egrep "[0-9]{4}-[0-9]{2}-[0-9]{2}|>RP<" )

test=`"$holidaysXML" | egrep "[0-9]{4}-[0-9]{2}-[0-9]{2}|>RP<"`

两者都没有给出预期的结果(与第一个代码片段不同)。谢谢你的任何建议。

2 个答案:

答案 0 :(得分:6)

写作时

"$holidaysXML" | egrep ...

$holidaysXML的值被解释为命令。最有可能的是,您的系统上没有这样的命令,因此没有输出可以发送到egrep。要将$holidaysXML的值发送到egrep,请使用

echo "$holidaysXML" | egrep ...

printf '%s\n' "$holidaysXML" | egrep ...

egrep ... <<< "$holidaysXML"

建议bash使用最后一个版本。对于可移植脚本,使用printfecho behaves differently表示不同的shell。

要保存输出,请将所有内容放入$(...)

myVariable="$(egrep ... <<< "$holidaysXML")"

答案 1 :(得分:1)

你所做的是部分正确的,即:

import { EventBus } from './event-bus.js'

then(response => {

    if(response.status == 200){
      setTimeout(function(){window.location.replace('url');
      }, 1500);
      this.logged = true;
      this.username = response.data.user.full_name;
      EventBus.$emit('login', this.username);
      console.log(this.username);

    } })

出了什么问题,您可能正在使用# This is correct test=$( echo "$holidaysXML" | egrep "[0-9]{4}-[0-9]{2}-[0-9]{2}|>RP<" ) # Attempting to echo test as you have mentioned will strip whitespaces echo $test 而不是echo $test回应。请记住,在双引号逗号内回显会强制bash保留空格,所以这应该有效:

echo "${test"}
相关问题