Script Question regarding finding and renaming a CSV file

General Tech Bugs & Fixes 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I am trying to write a script that starts off with f="https://forum.tuteehub.com/tag/testing">testing for the f="https://forum.tuteehub.com/tag/existence">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 "*.f="https://forum.tuteehub.com/tag/csv">csv" ];
   then
   cp *.f="https://forum.tuteehub.com/tag/csv">csv listing.txt
fi
profilepic.png
manpreet 2 years 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:

#!/bin/sh

set -- *.csv

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

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

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.


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.