Search code examples
linuxbashrenamefilenamestxt

Rename file as third word on it (bash)


I have several autogenerated files (see the picture below for example) and I want to rename them according to 3rd word in the first line (in this case, that would be 42.txt).

First line:

ligand CC@@HOc3ccccc3 42 P10000001

Is there a way to do it?


Solution

  • Say you have file.txt containing:

    ligand CC@@HOc3ccccc3 42 P10000001
    

    and you want to rename file.txt to 42.txt based on the 3rd field in the file.

    *Using awk

    The easiest way is simply to use mv with awk in a command substitution, e.g.:

    mv file.txt $(awk 'NR==1 {print $3; exit}' file.txt).txt
    

    Where the command-substitution $(...) is just the awk expression awk 'NR==1 {print $3; exit}' that simply outputs the 3rd-field (e.g. 42). Specifying NR==1 ensures only the first line is considered and exit at the end of that rule ensures no more lines are processed wasting time if file.txt is a 100000 line file.

    Confirmation

    file.txt is now renamed 42.txt, e.g.

    $ cat 42.txt
    ligand CC@@HOc3ccccc3 42 P10000001
    

    Using read

    You can also use read to simply read the first line and take the 3rd word as the name there and then mv the file, e.g.

    $ read -r a a name a <file.txt; mv file.txt "$name".txt
    

    The temporary variable a above is just used to read and discard the other words in the first line of the file.