Search code examples
bashunixfor-loopfilenamescut

Cannot echo bash variable from single line command


I have the following file names where I am trying to relabel v5.4b to v5.7:

v5.4b_lvl-1.e8974326
v5.4b_lvl-1.o8974326
v5.4b_lvl-1.pe8974326
v5.4b_lvl-1.po8974326
v5.4b_lvl-2.1.e8974303
v5.4b_lvl-2.1.o8974303
v5.4b_lvl-2.1.pe8974303
v5.4b_lvl-2.1.po8974303
v5.4b_lvl-2.2.e8974304
v5.4b_lvl-2.2.o8974304
v5.4b_lvl-2.2.pe8974304
v5.4b_lvl-2.2.po8974304
v5.4b_lvl-3.1.e8974305
v5.4b_lvl-3.1.o8974305
v5.4b_lvl-3.1.pe8974305
v5.4b_lvl-3.1.po8974305
v5.4b_lvl-4.1.e8974327
v5.4b_lvl-4.1.o8974327
v5.4b_lvl-4.1.pe8974327
v5.4b_lvl-4.1.po8974327

I can't do mv v5.4b_* v5.7_* because it thinks v5.7_* is a directory so I am trying a for-loop but I can't get it to work

I am trying the recommended answer from this SO post How to set a variable to the output of a command in Bash? but getting a bunch of empty lines.

What am I doing incorrectly? How can I save the output of cut to SUFFIX so I can mv $i v5.7_$SUFFIX?

-bash-4.1$ for i in v5.4b*; do echo $i | SUFFIX=`cut -f2 -d'_'`; echo ${SUFFIX}; done

Solution

  • You've got echo $i in the wrong place. The output of that command needs to be piped to cut for it to read anything, then the result is assigned to SUFFIX:

    for i in v5.4b*
    do 
        SUFFIX=`echo $i | cut -f2 -d'_'`
        echo ${SUFFIX}
    done