2

On my Linux machine, I want to remove the directories containing specific words that I stored in a parameter ($LIB_TO_REMOVE). But, when I used the wild card and parameter expansion (first ls to check), the shell does not interpret * as the wild card. Any suggestions? I'm expecting ls *${LIB_TO_REMOVE}* to list the first 3 directories.

$ ls
NG-23827_01_AD_02_BI_LS_01_F4_lib390563_6741_1_quant
NG-23827_01_AD_04_BI_LS_01_A7_lib390582_6741_1_quant
NG-23827_01_AD_04_BI_NL_02_B7_lib390583_6737_1_quant
NG-23827_01_AD_05_BI_LS_01_A11_lib390614_6741_2_quant
NG-23827_01_AD_05_BI_LS_02_A8_lib390590_6741_1_quant
NG-23827_01_AD_05_BI_NL_01_C9_lib390600_6741_1_quant
NG-23827_01_AD_06_BI_NL_02_E3_lib390554_6741_1_quant
NG-23827_01_AD_07_BI_LS_02_G5_lib390572_6741_1_quant
NG-23827_01_AD_07_BI_NL_02_F1_lib390539_6751_1_quant
NG-23827_01_AD_08_BI_LS_02_G8_lib390596_6741_1_quant
$ echo $LIB_TO_REMOVE 
lib390563 lib390582 lib390583
$ ls *${LIB_TO_REMOVE}*
ls: cannot access *lib390563: No such file or directory
ls: cannot access lib390582: No such file or directory
ls: cannot access lib390583*: No such file or directory
TU HU
  • 21
  • 3

1 Answers1

7

Your variable is a single string: lib390563 lib390582 lib390583. Therefore, assuming (based on the error message you are showing) the default word-splitting on white space, *${LIB_TO_REMOVE}* means "all files or directories whose name ends in the string lib390563 or is exactly equal to lib390582 or begins with the string lib390583". Since you have no files or directories whose name matches these criteria, nothing is shown. Here are a couple of possible workarounds:

  1. Since you presumably control the contents of the variable, you can probably safely do this:

    $ for i in $LIB_TO_REMOVE; do ls -d *"$i"*; done
    NG-23827_01_AD_02_BI_LS_01_F4_lib390563_6741_1_quant
    NG-23827_01_AD_04_BI_LS_01_A7_lib390582_6741_1_quant
    NG-23827_01_AD_04_BI_NL_02_B7_lib390583_6737_1_quant
    

    But be aware of the general issues about using unquoted variables.

  2. Use an array instead of a string for your variable:

    $ LIB_TO_REMOVE=(lib390563 lib390582 lib390583)
    $ for i in "${LIB_TO_REMOVE[@]}"; do ls -d *"$i"*; done
    NG-23827_01_AD_02_BI_LS_01_F4_lib390563_6741_1_quant
    NG-23827_01_AD_04_BI_LS_01_A7_lib390582_6741_1_quant
    NG-23827_01_AD_04_BI_NL_02_B7_lib390583_6737_1_quant
    
fra-san
  • 10,205
  • 2
  • 22
  • 43
terdon
  • 242,166