bash: how to delete elements from an array based on a pattern

前端 未结 6 1150
后悔当初
后悔当初 2020-12-03 07:26

Say I have a bash array (e.g. the array of all parameters) and want to delete all parameters matching a certain pattern or alternatively copy all remaining elements to a new

6条回答
  •  情书的邮戳
    2020-12-03 08:00

    To strip a flat string (Hulk has already given the answer for arrays), you can turn on the extglob shell option and run the following expansion

    $ shopt -s extglob
    $ unset x
    $ x="preffoo bar foo prefbaz baz prefbar"
    $ echo ${x//pref*([^ ])?( )}
    bar foo baz
    

    The extglob option is needed for the *(pattern-list) and ?(pattern-list) forms. This allows you to use regular expressions (although in a different form to most regular expressions) instead of just pathname expansion (*?[).

    The answer that Hulk has given for arrays will work only on arrays. If it appears to work on flat strings, its only because in testing the array was not unset first.

    e.g.

    $ x=(preffoo bar foo prefbaz baz prefbar)
    $ echo ${x[@]//pref*/}
    bar foo baz
    $ x="preffoo bar foo prefbaz baz prefbar"
    $ echo ${x[@]//pref*/}
    bar foo baz
    $ unset x
    $ x="preffoo bar foo prefbaz baz prefbar"
    $ echo ${x[@]//pref*/}
    
    $
    

提交回复
热议问题