Home > OS >  Save folder name as variable in a loop using bash
Save folder name as variable in a loop using bash

Time:05-11

I have multiple folders and I'm trying to save each folder name as a varible for downstream use in a loop:

for f in TINKER*;
do
name=$(echo $f | sed 's/TINKER_more([0-9] )_less([0-9] )/TINKER_$1_$2/')

echo $name done

Folder examples:

TINKER_more05_less23
TINKER_more55_less218
TINKER_more23_less03

In the case of the first folder above, I want echo $name to output: TINKER_05_23

For some reason, I have been getting empty output from echo $name.

Can anyone help? Thanks

CodePudding user response:

Bash has a built-in match operator =~, so you don't need sed for that. You can write your snippet in pure Bash, like the following:

for f in TINKER*; do 
    if [[ $f =~ TINKER_more([0-9] )_less([0-9] ) ]]; then
        echo TINKER_${BASH_REMATCH[1]}_${BASH_REMATCH[2]}
    fi
done

The code above will result in the following output for the files you posted:

TINKER_05_23
TINKER_23_03
TINKER_55_218

CodePudding user response:

The in POSIX BRE regex matches a literal char. You need to add an -E option to make sed use the POSIX ERE syntax.

Besides, you need to use \n, not $n, in the replacement. perl uses $n replacement backreference syntax, but sed uses \n.

So you need

sed -E 's/TINKER_more([0-9] )_less([0-9] )/TINKER_\1_\2/'

When testing with the above data,

fldrs="TINKER_more05_less23 TINKER_more23_less03 TINKER_more55_less218"
for f in $fldrs; do
 name=$(echo "$f" | sed -E 's/TINKER_more([0-9] )_less([0-9] )/TINKER_\1_\2/');
 # OR
 # name=$(sed -E 's/TINKER_more([0-9] )_less([0-9] )/TINKER_\1_\2/' <<< "$f");
 echo "$name"
done

The output is

TINKER_05_23
TINKER_23_03
TINKER_55_218

CodePudding user response:

Using sed

$ name=$(sed 's/_[^0-9]*\([^_]*\)/_\1/g' <<< $f)
  • Related