Bash: for do file name

Hi, I’m not used to doing something in Bash, so I am having some problems:

My goal is to look for special files in the folder, and if they are found, they generate some other files with the same file names, but different extensions.

Sort of:

For Files-that-are-called-"SysBackup*.Now" do NewFileName = ChangeFileExt(FoundFilename),BK GenerateNewfile(NewFileName) done 

The above is of course dummycode, I will not bother you with the code I made, since it does not work :-)

Therefore, the goal should be:

If the folder contains Sysbackup123.now and Sysbackup666.now, I get the files Sysbackup123.bk and Sysbackup666.bk

Thanks for any help

Michael

+4
source share
5 answers

Simple enough:

 for a in Sysbackup*.now; do [ -f $a ] && touch $(basename $a .now).bk ; done 
+8
source

Here's how I do it with sh :

 #!/bin/sh for file in SysBackup*.now; do if [ ! -e "$file" ]; then continue fi base=${file##*/} bk=${base%.now}.bk touch $bk done 
+2
source

Here is another way to make a replacement. Bash has the equivalent of sed s/string1$/string2/ , which uses the regular expression dollar sign to select the end of the pattern:

 for a in Sysbackup*.Now; do [ -f $a ] && touch "${a/%.Now/.BK}" done 

The percent sign matches at the end, and pound (#) matches at the beginning.

+2
source

You can do something like this:

 for F in SysBackup*.Now; do [ -f $F ] && touch $(echo "$F" | sed 's/Now$/BK/') done 

This uses echo to pass the names of the sed files, which changes the postfix string "Now" to "BK" . touch creates the file if it does not already exist. The new file will be empty. The [ -f $F ] test ensures that only files (not directories or symbolic links) are counted.

Alternatively, you can use find . An example using basename as shown in Stephen Darlington's answer :

 find . -type f -iname "SysBackup*.Now" -exec sh -c "touch \$(basename '{}' .Now).BK" \; 

Note that in both examples, it is important to place quotation marks around file names to ensure that file names with spaces are correctly processed.

+1
source

here is another way if you do not want to use for the loop and check if its file is or not

 find /path -maxdepth 1 -type f -name "Sysbackup*now" | while read file do touch "${file/%.now/.bK}" done 
0
source

All Articles