How to change file names in Shell Script?
Andrew Henderson
I have a task to rename a bunch of files to their content at row1 colum2 (a string). The files do not have extensions. I also have to add .pdb as an extension to every file.
so far I've written this and it does not work :(
#! /bin/bash
for f in sequences/*; do
mv "$f" "($ awk 'NR==1 {print=$2}').pdb";
doneI am very very new to Shell script and still have no idea how to use it. Any help would be appreciated!
72 Answers
A few things to note:
the syntax for command substitution is
$( command )not($ command )the syntax for printing the second field in awk is
print $2notprint=$2you need to pass the name of the file as an argument to awk ex.
awk 'NR==1 {print $2}' "$f"
Also note that the new file will be created relative to the current directory, rather than the subdirectory sequences (there's not enough detail in your question to know whether that's the intended outcome or not).
Thank you steeldriver! The remarks helped a lot! The 3rd one was the real problem solver! So here's the script I wrote in the end:
#! /bin/bash
for f in $(ls); do
mv "$f" "$( awk 'NR==1 {print $2}' "$f" ).pdb";
doneIf anyone has any 'smarter' ways of doing it I would be very happy to hear them.
Thanks!
2