sedは、2つのパターン(そのうちの1つは変数)から一致するものを検索して削除します。

sedは、2つのパターン(そのうちの1つは変数)から一致するものを検索して削除します。

削除する必要がある複数のコードインスタンスを含むファイルがあります。例は次のとおりです。

!/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と入力し、特定のサンプル(サンプル_1_NA172_1など)を検索し、mkdir行とそれに続く13行(それ以外のすべてのサンプル)を削除できる必要があります。場合によっては、いくつかの例のコードスニペットを維持する必要がありますが、最初は1つの操作しか実行しようとしません。

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

おすすめ記事