See More
Popular Forum

MBA (4887) B.Tech (1769) Engineering (1486) Class 12 (1030) Study Abroad (1004) Computer Science and Engineering (988) Business Management Studies (865) BBA (846) Diploma (746) CAT (651) B.Com (648) B.Sc (643) JEE Mains (618) Mechanical Engineering (574) Exam (525) India (462) Career (452) All Time Q&A (439) Mass Communication (427) BCA (417) Science (384) Computers & IT (Non-Engg) (383) Medicine & Health Sciences (381) Hotel Management (373) Civil Engineering (353) MCA (349) Tuteehub Top Questions (348) Distance (340) Colleges in India (334)
See More

Script Question regarding finding and renaming a CSV file

General Tech Bugs & Fixes
Max. 2000 characters

Dilpreet Kaur


( 7 months ago )


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.

if [ -f "*.csv" ];
   cp *.csv listing.txt

Sarah Jones


( 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:


set -- *.csv

while [ "$#" -gt 0 ] && [ ! -f "$1" ]; do

if [ -f "$1" ]; then
    mv -- "$1" listing.txt

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(-.[1]) 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.

what's your interest