与えられた文字列を含む範囲内のスクリプトから行を削除する方法は?

与えられた文字列を含む範囲内のスクリプトから行を削除する方法は?

タイトルが自明だと思います。パラメータとして与えられたいくつかのファイルがあり、与えられた文字列は私のスクリプトの最後のパラメータです。以下の両方のスクリプトを試しましたが、両方を機能させる方法がわかりません。 sedコマンドで検索するパターン(文字列)を指定する両方のスクリプトで、一部の「\」文字が欠落しているようです。

#!/bin/bash
a=${@: -1} # get last parameter into a variable
or ((i=1; i<$#; i++)) # for each parameter, except the last one
    do
        sed -i '1,30{/$a/d}' "${!i}" # delete each line in the i-th file, in range 1-30
                                      # containing $a (last given parameter)
    done

2回目の試み:

#!/bin/bash
a=${@: -1} # get last parameter into a variable
for file in "${@:1:$# - 1}"
do
    sed -i '1,30{/$a/d}' $file
done

ベストアンサー1

私の問題は、二重引用符ではなく一重引用符を使用することです。変数拡張不可能。

以下は、@guillermo chamorroが要求した入力ファイルと出力ファイル、および端末からスクリプトを呼び出す例と一緒に2つの作業スクリプトです(ここで「call」という単語を正しく使用しているかどうかはわかりません。「using」と仮定します)。 :

ファイル1ファイル2同じ内容があります)

Out of the first 30 lines of this file I will be deleting only those that contain 
the character substring given as a parameter.
2
3
4
5
6
7
8
9
10
11
12    
13
14
15
16
17
18
19
30
31
32
33
...
and so on

function_shell_1

#!/bin/bash
a=${@: -1} # store last argument in a variable

    #part of the for-loop line is commented because of the first hashtag character

for ((i=1; i<$#; i++)) # consider all arguments, but the last one
do
    sed -i "1,30{/$a/d}" "${!i}" 
    # for each i-th line among the first 30 lines, do in-place deletions 
    #(-i dictates the in-place part) of each one containing the value of the
    # a variable
done

function_shell_2(forループへのマイナーな変更のみ)

#!/bin/bash
a=${@: -1} # store last argument in a variable

for fisier in "${@:1:$# - 1}" # consider all arguments, but the last one
do
    sed -i "1,30{/$a/d}" $fisier         
    # for each i-th line among the first 30 lines, do in-place deletions 
    #(-i dictates the in-place part) of each one containing the value of the
    # a variable
done

スクリプトコマンドの例:

./function_shell_1 file1 file2 '2'
#./function_shell_2 file1 file2 '2'

上記の両方はまったく同じように動作し、両方とも同じ予想変更を生成します。ファイル1そしてファイル2、つまり:

Out of the first 30 lines of this file I will be deleting only those that contain
the character substring given as a parameter.
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
31
32
33
...
and so on

おすすめ記事