Question

I have a list of 87 text files populated daily in UNIX.

Eg: FP*.txt --- file names start with FP & are txt files Daily new content gets appended to the end. I want to take a back up of all the text files using shell script and create blank files of the same name. I tried the following.

echo "" > FP*.txt

and > FP*.txt

Both gave the same error.

FP*.txt: ambiguous redirect

however when used on single file both work fine. So how to resolve it. And also creating a list of hard-coded names is not an option, as 87 are too many and they may increase in future.

Also some file names contain ( & , in their names. When tried the following codes,

echo "" > FP---Sample.txt

This worked fine. But when tried the following gave error.

echo "" > FP(1)---Sample.txt

This gave an error.

syntax error near unexpected token `('

So how to accomplish it??

Was it helpful?

Solution

Wrap the filename in quotes:

echo "" > "FP(1)---Sample.txt"

OTHER TIPS

You get a

FP*.txt: ambiguous redirect

because you can just redirect to one file, while FP*.txt expands to more than one. That's why it works when the expansion just returns one name.

To do what you need, you'd better loop through the results of FP*.txt. For example, you can use:

bk_date=$(date "+%Y%m%d_%H%M%S")       # 20140210_150526 format of date
for file in FP*.txt
do
   cp -p "$file" "${file}.${bk_date}"  # make a backup of the file
   > "$file"                   # blank it. This is same as echo "" > "$file"
done

Regarding the error:

syntax error near unexpected token `('

Martin Dinov correctly explained that you need to quote the name to make it be part of the file name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top