chuckfinley
chuckfinley

Reputation: 763

bash for loop, use input filename in the output filename

I want to use my input filename (baseline.YYYYMM.tar) in my output filename (baseline.YYYYMM.var1.tar). I can process the input files but don't know how to pass the output filename I need to my cdo application:

#!/bin/bash

prefix="basename"
fndate=$(ls | grep tar|cut -c 10-15)
var="var1"
extension=".tar"
outputfile=$prefix $fndate $var $extension
for f in $(find . -name "*.tar" -print) ; do
cdo selname,var1 $f $outputfile
done

thanks

Upvotes: 2

Views: 1606

Answers (2)

Walter A
Walter A

Reputation: 19982

(I agree with remarks about parsing ls.) Did you forget dots?

 outputfile=$prefix $fndate $var $extension

should be

outputfile=${prefix}.${fndate}.${var}${extension}

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74596

I'm not 100% sure I get what you're trying to do but if I'm right, you should be able to use something like this to get your output file name from the input:

var=var1
for f in *.tar; do
    output=$(awk -v s="$var" 'BEGIN{FS=OFS="."}{print $1, $2, s, $3}' <<<"$f")
    # use "$output" however you want, e.g.
    echo "$output"
done

This uses awk to split up the input file name $f and insert the shell variable $var in the middle. <<<"$f" is bash syntax, equivalent to echo "$f" | at the start of the command.

Upvotes: 0

Related Questions