macosunixqiime

Adding a character string to every line in a file, incrementing that character string added by 1 each file


I have some set of files with character strings in lines such that there is a folder containing

file1
file2
file3

and within those files there a variable length lists of strings of characters such that file 1 may read

file1.itemA
file1.itemB
file1.itemC

While file 2 may only contain

file2.itemA
file2.itemB

I want to add a file specific code to every line within each file such that

code1.file1.itemA
code1.file1.itemB
code1.file1.itemC

And

code2.file2.itemA
code2.file2.itemB

How can I do this within unix? I am using the OSX terminal to execute commands.


Solution

  • I'm not near a terminal to test, but, how about:

    cd /path/to/your/files
    word='code'
    base=1
    for file in *; do sed -i -e "s/^/$word$base/" "${file}"; base=$(( $base + 1 )); done
    

    The $word variable is the constant you want. The $base variable holds the count that is incremented on each file, initially set to 1.