sed 搜索和删除匹配两种模式,其中之一是变量

sed 搜索和删除匹配两种模式,其中之一是变量

我有一个文件,其中包含需要删除的多个代码实例。这是一个例子:

!/bin/bash
mkdir /rootdir/pipeline_runs/oncology/analysis/sample_1_NA172_1
cd /rootdir/pipeline_runs/oncology/analysis/sample_1_NA172_1
ln -s ../oncology/importantFile1 importantFile1
ln -s ../oncology/importantFile2 importantFile2

mkdir /rootdir/pipeline_runs/oncology/analysis/sample_2_NA172_2
cd /rootdir/pipeline_runs/oncology/analysis/sample_2_NA172_2
ln -s ../oncology/importantFile1 importantFile1
ln -s ../oncology/importantFile2 importantFile2

mkdir /rootdir/pipeline_runs/oncology/analysis/sample_3_NA172_3
cd /rootdir/pipeline_runs/oncology/analysis/sample_3_NA172_3
ln -s ../oncology/importantFile1 importantFile1
ln -s ../oncology/importantFile2 importantFile2

实际上,此脚本中可能有 16 到 30 个这样的内容。我需要能够 sed 进入此文件并搜索给定样本(例如sample_1_NA172_1)并删除 mkdir 行及其后面的 13 行(除此之外的所有样本)。在某些情况下,我需要保留多个示例的代码片段,但一开始我会尝试只做一个工作。

fileToEdit=above-mentioned-script.sh

# This pulls out the first line of each mkdir snippet along with the 
# sample name.
mkdirList=$(grep -E mkdir $fileToEdit)

# Removes the mkdir from output and cuts 
# all the dir path leaving just the sample name
sample=$(echo $mkdirList | sed 's/mkdir //g' | tr ' ' '\n' | cut -d/ -f14-)

printf "\n"
echo "Which sample(s) would you like to keep?"
printf "\n"

# Dynamic Menu Function
createmenu () {
select selected_option; do # in "$@" is the default
    if [ 1 -le "$REPLY" ] && [ "$REPLY" -le $(($#)) ]; then
        break;
    else
        echo "Please make a vaild selection (1-$#)."
    fi
done
}

declare -a tsample=();

# Load Menu by Line of Returned Command
mapfile -t tsample < <(echo $sample | tr ' ' '\n');

# Display Menu and Prompt for Input
echo "(Please select one):";
.
# This generates a dynamic numbered menu list of all the samples.
# Currently it allows the user to choose one sample to keep.
# Eventually I'd like to allow them to choose multiple samples. 
createmenu "${tsample[@]}"

# This is the sample that was chosen
tsample=($echo "${selected_option}");

# This greps all the samples BUT the chosen sample and makes it a variable.
rsample=$(echo $sample | tr ' ' '\n' | grep -v $tsample)

# This is my attempt to make an array out of the remaining samples
# that need to be deleted, and then sed search/delete them from the script.
declare -a array=( "echo $rsample" )
for i in "${!array[*]}"
    do
            sed -i '/mkdir.*$i/,+13 d' $fileToEdit
    done

我已经验证我可以成功使用:

sed -i /mkdir.*sample_1_NA172_1/,+13 d'

我认为我的阵列没问题。我认为我的问题是在 sed 搜索字段内的“*”旁边使用 $i 。

所以:

  1. 我试图让 sed 使用针对数组的通配符工作。
  2. 我想把它放在可以接受多个样本保存的地方。

答案1

将单引号更改为双引号是否有效?:

sed -i "/mkdir.*$i/,+13 d" $fileToEdit

关于什么 :

 sed -i "/mkdir.*${i}/,+13 d" $fileToEdit

相关内容