Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to change file names in Shell Script?

Writer 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";
done

I am very very new to Shell script and still have no idea how to use it. Any help would be appreciated!

7

2 Answers

A few things to note:

  1. the syntax for command substitution is $( command ) not ($ command )

  2. the syntax for printing the second field in awk is print $2 not print=$2

  3. you 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";
done

If anyone has any 'smarter' ways of doing it I would be very happy to hear them.

Thanks!

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy