Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm using a bash commandline for-loop to concat a group of files together, and I'd like to append an incrementing digit.

Something like this:

j=1;for i in *.bak; do echo {$j++: >> files.grp;cat $i >> files.grp; echo }, >> files.grp; done

So the output would like this:

{1:"file1 contents"},{2:"file2 contents"},
share|improve this question
add comment

2 Answers 2

up vote 6 down vote accepted

What you need to do is:

j=$(($j+1))

or use

$((j++))
share|improve this answer
add comment
# file1.bak
hallo

# some other file.bak
H?llo*

# a!file.bak
new!
line"

Processed with the script:

j=1
for i in *.bak; do
  echo "{$((j++)):$(cat "$i")}" >> files.grp
done

Writes the following in files.grp:

{1:hallo}
{2:H?llo*}
{3:new!
line"}
share|improve this answer
    
Oh very nice. Can you explain what $(cat "$i") is doing? That is, I understand what the output of that will be, based on your example, but what does that syntax mean? –  Alan Jan 26 '11 at 9:26
    
This is called command substitution. $(command) will execute command and print the output of it (if any). In this case, echo will receive the output of cat "$i" as an input and processes that further. See the section 'Command Substitution' in man bash –  wag Jan 26 '11 at 9:41
    
thank you! –  Alan Jan 26 '11 at 18:34
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.