简体   繁体   中英

How to obtain new filename from old filename in the shell script?

I have an executable program that have input and output likes

./my_exe -i filename_input -o filename_output 

I want to use the program to run all filename in my folder that has structure likes

root
|-folder_A
   |-abc.txt
|-folder_B
   |cdf.txt

So, we can use for to do it. But the problem is that I want to automatically make the filename_output from the filename_input by adding the extension '_processed' before '.txt' likes abc.txt is input file name . Then the output will be abc_processed.txt

How to do it in shell script? This is my current for code

for sub_folder in "${root_folder[@]}"
        do            
            filename_input=$sub_folder/*.txt
            filename_output= filename_input/*.txt/processed.txt
            echo filename_output
        done

The output of my script is root/folder_A/*processed.txt . I do not know why abc is lost

$ tree root
root
|-- directory-A
|   `-- abc.txt
`-- directory-B
    `-- def.txt

2 directories, 2 files
$ find root -type f -exec sh -c 'echo ${1%.txt}_processed.txt' _ {} \;
root/directory-B/def_processed.txt
root/directory-A/abc_processed.txt

or:

$ for dir in root/*; do ( cd $dir; for file in *.txt; 
    do echo "$file --> ${file%.txt}_processed.txt"; done ) done
abc.txt --> abc_processed.txt
def.txt --> def_processed.txt

The right solution depends on what you want to do with it.
You should loop over the files you want to rename, not the directories.

for f in */*/*txt; do
   echo "With path ${f} ==> ${f//.txt/processed.txt}"
   base_f=${f##*/}
   echo "Basenames: ${base_f} ==> ${base_f//.txt/processed.txt}"
done

You might want to use find ... | xargs find ... | xargs for this when you want to call my_exe with these files.
Make sure your *processed.txt are not converted again!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM