使用sed检查$ 1以有条件地替换路径字符串中最后出现的单词

时间:2017-06-21 09:45:55

标签: bash sed

我有一个包含完整路径名的变量。我试图有条件地替换路径中最后一个单词的出现。用于显示我正在尝试的示例脚本

#!/bin/sh

testvar="/home/downloads/user/downloads"

if [ "$1" = "alternate" ]; then
  newtestvar=$(echo $testvar | sed -e 's/\(.*\)downloads$/\1alternate_downloads/g')
else
  newtestvar=$(echo $testvar | sed -e 's/\(.*\)downloads$/\1new_downloads/g')
fi

echo "testvar:" $testvar
echo "newtestvar:" $newtestvar

运行#1

$ ./foofile
testvar: /home/downloads/user/downloads
newtestvar: /home/downloads/user/new_downloads

运行#2

$ ./foofile alternate
testvar: /home/downloads/user/downloads
newtestvar: /home/downloads/user/alternate_downloads

我确实得到了预期的结果,但我正在寻找一种避免if / else的方法,而是通过检查sed上下文中的$ 1来实现结果。

修改-1

我用以下简写替换了if/else块。但它看起来很笨拙,难以阅读。

newtestvar=$([[ $1 = "alternate" ]] && echo $testvar | sed -e 's/\(.*\)downloads$/\1alternate_downloads/g' || echo $testvar | sed -e 's/\(.*\)downloads$/\1new_downloads/g')

2 个答案:

答案 0 :(得分:2)

您可以避免input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x_train}, y_train, batch_size=4, num_epochs=1000) eval_input_fn = tf.contrib.learn.io.numpy_input_fn({"x":x_eval}, y_eval, batch_size=4, num_epochs=1000) # We can invoke 1000 training steps by invoking the method and passing the # training data set. estimator.fit(input_fn=input_fn, steps=1000) # Here we evaluate how well our model did. train_loss = estimator.evaluate(input_fn=input_fn) eval_loss = estimator.evaluate(input_fn=eval_input_fn) print("train loss: %r"% train_loss) print("eval loss: %r"% eval_loss) 并在bash中处理此问题:

sed

现在称之为:

#!/bin/bash

testvar="/home/downloads/user/downloads"

# default s to "new"
s="${1:-new}"

# replace only last value of downloads
newtestvar="${testvar/%downloads/${s}_downloads}"

# examine both variables
declare -p testvar newtestvar

答案 1 :(得分:1)

sed可能无法做到这一点,因为sed无法测试变量的值,然后有条件地执行分支。

但是,可以使用AWK完成:

#!/bin/sh

testvar="/home/downloads/user/downloads"

newtestvar=$(awk -v arg="$1" '{
    replacement = arg == "alternate" ? "alternate_downloads" : "new_downloads";
    sub("downloads$", replacement);
    print $0;
  }
' <<<"$testvar")

echo "testvar:" $testvar
echo "newtestvar:" $newtestvar