Search code examples
bashprependletter

Prepend a letter to each line of a text, in ascending order


A bash script writes its output, which is a list of files, into a file.

file.txt:

/home/user/dir1/dir2/foo00
/home/user/dir1/dir2/foo01
/home/user/dir1/dir2/foo02

I want to prepend a letter to each line, starting with a, and after having reached z, going on with aa, ab…

in the end, the output should look like

file.txt:

a /home/user/dir1/dir2/foo00
b /home/user/dir1/dir2/foo01
c /home/user/dir1/dir2/foo02
...
z /home/user/dir1/dir2/foo26
aa /home/user/dir1/dir2/foo27

Being a newbie in shell scripting, I have no clue, which tool may be appropriate. I So my question keeps surely somewhat imprecise.

I'd prefer bash built ins, if possible.

How can I do this operation?


Solution

  • Using only bash builtins, without subshells:

    prefixes=({a..z}  {a..z}{a..z}  {a..z}{a..z}{a..z})
    i=0
    while IFS= read -r line
    do
      printf "%s %s\n" "${prefixes[i++]}" "$line"
    done < file.txt