-3

beginner here. I want to write a simple script for use in the bash terminal, but I don't know how to make it. The gist is that I have a folder filled with different files, some .foo, some .bar, etc. I want to create a script that takes all the .foo files and perform a command on them, but in the same line rename them so that the output file is named file.baz.

For example: command -i file.foo -o file.baz for all .foo files in a directory.

0

1 Answer 1

0

Renaming

You can use the rename command:

$ rename .foo .baz *.foo

Note that on some systems rename points to prename which uses a different syntax:

$ prename 's/.foo$/.baz' *.foo

Use man rename to find out which one you have.

Looping over files and running a command on each of them

You can provide the file list directly on the command line, using a globbing pattern:

$ your_script *.foo

Your script can then iterate over the list like this (using your command's usage):

for file in "$@"; do
    your_command -i "$file" -o "${file%.*}.baz"
done

${file%.*} resolves as the name of the file without its extension (file.foo -> file). More information on string manipulation is available here.

Sign up to request clarification or add additional context in comments.

2 Comments

for command in "$@", of course, my bad. I didn't know about the command built-in, will look into it, thanks
Looks good. Only thing I might add is a pointer on how to generate an output file name at the same time, ie. for file in *.foo; do your_command -i "$file" -o "${file%.foo}.baz"; done or such.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.