I am trying to write a script that starts off with testing for the existence of a CSV file. If it finds one, rename it to listing.txt.
This is what I have but it doesn't work.
cp *.csv listing.txt
( 7 months ago )
Your existing code tests for the existence of a file called *.csv (literally). This is why it does not work. It does that because the * is within double quotes.
Using [ -f *.csv ] will not work as expected if there are multiple files matching the pattern. If there are multiple files matching *.csv, the cp command will additionally not work properly, unless listing.txt is the name of a directory.
To rename the first of the files matching the filename globbing pattern *.cvs in the current directory, do this:
This first sets the positional parameters, $1, $2, etc., the all names matching *.csv in the current directory. Then it starts looking for the first regular file, or symbolic link to a regular file, among the matched names (the code assumes that the *.csv glob may expand to directory names etc.). If a regular file, or a symbolic link to one, is found, it renames that file to listing.txt.
In the zsh shell:
mv --*.csv(-.) listing.txt
This uses a glob modifier for the *.csv globbing pattern that returns the first regular file or symbolic link that matches the pattern.